﻿using AutoMapper;
using Dapper;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Hangfire;
using housingsafety.server.Caching.Core;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Repository;
using housingsafety.server.Repository.Extensions;
using housingsafety.server.Svcs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql;
using Npoi.Mapper;
using NPOI.HPSF;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Asn1.Ocsp;
using Quartz.Util;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static housingsafety.server.Controllers.HouseMngController;
using static housingsafety.server.Controllers.SampleTaskController;

namespace housingsafety.server.Controllers
{
    /// <summary>
    /// 大屏基本信息 展示
    /// </summary>
    [AllowAnonymous]
    public class HouseMngCheckHouseController : BaseController<HouseMngCheckController>
    {
        public IConfiguration Configuration { get; }
        private readonly IRepository<ZmVillageFireSafety> _villageFireSafetyRepository;
        private readonly ICache _cache;
        private readonly IMapper _mapper;
        private readonly IStorageProvider _storageProvider;
        private readonly ZmDbContext _dbContext;
        private readonly IRepository<ZmUser> _userRepository;
        private readonly IRepository<ZmBuildings> _buildingsRepository;
        private readonly IRepository<ZmBuildingsLayer> _buildingsLayerRepository;
        private readonly IRepository<ZmUpdateLog> _zmupdateRepository;
        private readonly IRepository<ZmUpdateLog> _zmupdate;
        private readonly IRepository<ZmFileAttach> _fileAttachRepository;
        private readonly IRepository<ZmPlaceCommercial> _placeCommercialRepository;
        private readonly IRepository<ZmPlaceResident> _placeResidentRepository;
        private readonly IOptions<StaticDataConf> _staticVtOptions;
        private readonly IRepository<ZmDepartment> _departmentRepository;
        private readonly IRepository<RiskCensusHouseYhpc> _riskHouseRepository;
        private readonly IRepository<RiskCensusYhpcUpldFile> _riskHouseFileRepository;
        private readonly IRepository<ZmPlaceResidentCheck> _placeResidentCheckRepository;
        private readonly IRepository<ZmPlaceCommercialCheck> _placeCommercialCheckRepository;
        private readonly IRepository<ZmYtPhoto> _zmYtPhotoRepository;
        private readonly IDbTransaction _transaction;

        private readonly Microsoft.AspNetCore.Http.Features.FormOptions _defaultFormOptions = new Microsoft.AspNetCore.Http.Features.FormOptions();
        private readonly string[] _permittedExtensions = { ".mp3", ".mp4", ".jpg", ".jpeg", ".png", ".geojson", ".doc", ".docx" };

        private static object _lock = new object();

        public HouseMngCheckHouseController(IStorageProvider storageProvider
            , IRepository<ZmDepartment> departmentRepository
            , IRepository<ZmUser> userRepository
              , IRepository<ZmVillageFireSafety> villageFireSafetyRepository
              , IRepository<ZmBuildings> buildingsRepository
            , IRepository<ZmBuildingsLayer> buildingsLayerRepository
            , IRepository<ZmFileAttach> fileAttachRepository
            , IRepository<ZmPlaceCommercial> placeCommercialRepository
            , IRepository<ZmPlaceResident> placeResidentRepository
            , IRepository<RiskCensusHouseYhpc> riskHouseRepository
            , IRepository<RiskCensusYhpcUpldFile> riskHouseFileRepository
            , IRepository<ZmPlaceResidentCheck> placeResidentCheckRepository
            , IRepository<ZmPlaceCommercialCheck> placeCommercialCheckRepository
            , IRepository<ZmYtPhoto> zmYtPhotoRepository
            , IMapper mapper, ICacheProvider cacheProvider, ZmDbContext dbContext
            , IOptions<StaticDataConf> staticVtOptions
            , ILogger<HouseMngCheckController> logger,
            IConfiguration configuration
            , IRepository<ZmSystemLog> systemLogRepository, IRepository<ZmUpdateLog> zmupdateRepository) : base(logger, systemLogRepository)
        {
            _zmupdateRepository = zmupdateRepository;
            _storageProvider = storageProvider;
            _mapper = mapper;
            _dbContext = dbContext;
            _cache = cacheProvider.CreateCache();
            _zmYtPhotoRepository = zmYtPhotoRepository;
            _userRepository = userRepository;
            _buildingsRepository = buildingsRepository;
            _buildingsLayerRepository = buildingsLayerRepository;
            _fileAttachRepository = fileAttachRepository;
            _placeCommercialRepository = placeCommercialRepository;
            _placeResidentRepository = placeResidentRepository;
            _staticVtOptions = staticVtOptions;
            _departmentRepository = departmentRepository;
            _riskHouseRepository = riskHouseRepository;
            _riskHouseFileRepository = riskHouseFileRepository;
            _placeResidentCheckRepository = placeResidentCheckRepository;
            _placeCommercialCheckRepository = placeCommercialCheckRepository;
            Configuration = configuration;
            _villageFireSafetyRepository = villageFireSafetyRepository;
            _zmupdateRepository = zmupdateRepository;

        }

        List<string> stringList = new List<string> { "栋", "栋", "处", "处" };




        /// <summary>
        /// 动态矢量瓦片服务(支持编辑)
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="z"></param>
        /// <returns></returns>
        [HttpGet("houses/dynamic/vector/tiles")]
        public ActionResult GetIntelLayerVt([FromQuery] int x, [FromQuery] int y, [FromQuery] int z)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return BadRequest("user not login");
            }

            var tile = GetDynamicVectorTile(z, x, y);
            return File(tile, "application/vnd.mapbox-vector-tile");
        }

        [HttpGet("houses/dynamic/vector/tiles_build")]
        public ActionResult GetDynamicVectorTilebuild([FromQuery] int x, [FromQuery] int y, [FromQuery] int z)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return BadRequest("user not login");
            }

            var tile = GetDynamicVectorTile__build(z, x, y);
            return File(tile, "application/vnd.mapbox-vector-tile");
        }






        /// <summary>
        /// 隐患发现地图
        /// </summary>
        /// <param name="type">统计方式：0/1/2 全北京/区/街道</param>
        /// <returns></returns>
        [HttpGet("houses/hidden-danger/stat")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<HiddenDangerStatDto>>), 200)]
        public RespRet<List<HiddenDangerStatDto>> StatHiddenDangerInfo([FromQuery] int type)
        {
            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<List<HiddenDangerStatDto>>(false, "user not logined");
            }


            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            if (null == user)
            {
                return new RespRet<List<HiddenDangerStatDto>>(false, "用户名不存在");
            }

            //DateTime dstartDate = DateTime.Parse("2023-02-09 00:00:00");
            //DateTime dendDate = DateTime.Parse("2025-03-09 00:00:00");
            //dstartDate = dstartDate.AddDays(1).AddSeconds(-1);


            var sbSql = new StringBuilder();

            if (type == 0)
            {
                sbSql.Append($@" 
SELECT 
  (SELECT COUNT(fwbh) FROM map_yh) AS hbyhcount,
  (SELECT COUNT(fwbh) FROM map_yh WHERE zcyhcount IS NOT NULL) AS zcyhcount,
  (SELECT COUNT(fwbh) FROM map_yh WHERE jcyhcount IS NOT NULL) AS jcyhcount


");
            }
            else if (type == 1)
            {

                sbSql.Append($@" 
	
	SELECT 
  xzqdm  as code,
  COUNT(fwbh) AS hbyhcount,
  COUNT(CASE WHEN zcyhcount IS NOT NULL THEN 1 END) AS zcyhcount,
  COUNT(CASE WHEN jcyhcount IS NOT NULL THEN 1 END) AS jcyhcount
FROM map_yh
GROUP BY xzqdm;

");
            }
            else if (type == 2)
            {

                sbSql.Append($@" 
	SELECT 
  towndm  as code,
  COUNT(fwbh) AS hbyhcount,
  COUNT(CASE WHEN zcyhcount IS NOT NULL THEN 1 END) AS zcyhcount,
  COUNT(CASE WHEN jcyhcount IS NOT NULL THEN 1 END) AS jcyhcount
FROM map_yh
GROUP BY towndm;
					


");

            }

            var datas = _dbContext.Database.GetDbConnection().Query<HiddenDangerStatDto>(sbSql.ToString()).ToList();
            return new RespRet<List<HiddenDangerStatDto>>(true, "Ok", datas);
        }

        #region 检查率
        /// <summary>
        /// 获取北京市自查率、检查率和核查率
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkrate")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRate>>), 200)]
        public RespRet<Page<BuildingPcRate>> HouseMngCheck([FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRate>>(false, "PageIndex must >= 0");
            }

            //var userNumber = this.CurrentUser();
            // if (string.IsNullOrEmpty(userNumber))
            //{
            //return new RespRet<Page<BuildingPcRate>>(false, "user not logined");
            //}
            string sql = @"select *,round((zccount*1.00/zcount)*100,2)|| '%' zcl,round((jccount/zcount)*100,2)|| '%' jcl,round((hccount/zcount)*100,2)|| '%' hcl   from 
                       ( select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.jccount,0)  jccount,coalesce(t4.hccount,0)  hccount from (select count(fwbh) zcount,'北京市' as xzq  from zm_buildings) t1 left join 
                       (select coalesce(count(fwbh),0)  zccount,'北京市' as xzq from (select distinct(fwbh) fwbh from zm_pc_yh ) tt )t2 on t1.xzq=t2.xzq  
                       left join 
                       (select coalesce(count(fwbh),0)  jccount,'北京市' as xzq from (select distinct(fwbh) fwbh from zm_pc_yh_cj ) tt )t3 on t1.xzq=t3.xzq  
                       left join 
                       (select coalesce(count(fwbh),0)  hccount,'北京市' as xzq from (select distinct(fwbh) fwbh from zm_pc_yh_xz ) tt )t4 on t1.xzq=t4.xzq 
                       )  tt   limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRate>(sql).ToList();
            int count = list.Count;
            var pageData = new Page<BuildingPcRate>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRate>>(true, "Ok", pageData);
        }


        private object JsonRegion(string jsonStr)
        {
            try
            {
                return JsonConvert.DeserializeObject<object>(jsonStr);
            }
            catch (System.Exception)
            {
            }

            return null;
        }


        /// <summary>
        /// 人员疏散通道情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/rysstdqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> Dbltable([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null)
                {
                    return new RespRet<object>(false, "请传递参数");
                }
                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                param.code = param.code.Replace("000", "");



                string time = DateTime.Today
 .AddHours(23)
 .AddMinutes(59)
 .AddSeconds(59)
 .ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;

                string sql = @"  ";
                if (param.code.Length == 3)
                {
                    sql = @" select zzsggz,zzzdfa,jzswhntjzssslt,jzsnzssslt,lyxlhxjjzss,zcount,ydb,wdb,dbl||'%' dbl,name xzq,code xzqdm from  dblbar_gq_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@tablename) ";
                }
                if (param.code.Length == 6)
                {
                    sql = @" select zzsggz,zzzdfa,jzswhntjzssslt,jzsnzssslt,lyxlhxjjzss, zcount,ydb,wdb,dbl||'%' dbl,name town,code towndm from  dblbar_xz_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@code,@tablename)  ";
                }
                if (param.code.Length == 9)
                {
                    sql = @" select  zzsggz,zzzdfa,jzswhntjzssslt,jzsnzssslt,lyxlhxjjzss,zcount,ydb,wdb,dbl||'%' dbl,name village,code villagedm from  dblbar_cj_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@code,@tablename) ";
                }
                if (param.code.Length == 12)
                {
                    sql = @" select zzsggz,zzzdfa,jzswhntjzssslt,jzsnzssslt,lyxlhxjjzss, zcount,ydb,wdb,dbl||'%' dbl,name village,code villagedm from  dblbar_cj_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@code,@tablename)	 ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new {@tablename=table_name,@time=time, @code = "%" + param.code + "%" }).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/rysstdqk", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), ex.ToString());
                WriteSystemLog(usernNumber, "houses/rysstdqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }

        /// <summary>
        /// 人员疏散通道情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/rysstdqkmsg")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> rysstdqkmsg([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null)
                {
                    return new RespRet<object>(false, "请传递参数");
                }
                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                param.code = param.code.Replace("000", "");

                string time = DateTime.Today
 .AddHours(23)
 .AddMinutes(59)
 .AddSeconds(59)
 .ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;

                string zsql = $@" select zcount,ydb,wdb,dbl||'%' dbl from  rysstd_gq_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@table_name)  ";
                var data = _dbContext.Database.GetDbConnection().Query<object>(zsql, new {@time=time, @code = "%" + param.code + "%",@table_name }).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/rysstdqkmsg", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), ex.ToString());
                WriteSystemLog(usernNumber, "houses/rysstdqkmsg", res);
                res.Msg = "系统异常";
                return res;
            }
        }




//        /// <summary>
//        /// 防火委平台接口  接口中提供自建房总数、周自查率、人员疏散通道已达标数、未达标数、达标率
//        /// </summary>
//        /// <param name="pageRequest"></param>
//        /// <returns></returns>
//        [HttpPost("houses/GetZcData")]
//        [Produces("application/json")]
//        [ProducesResponseType(typeof(RespRet<object>), 200)]

//        public RespRet<object> GetZcData([FromBody] DateQuery param)
//        {
//            var usernNumber = this.CurrentUser();
//            try
//            {
//                if (param == null)
//                {
//                    return new RespRet<object>(false, "请传递参数");
//                }
//                if (string.IsNullOrWhiteSpace(param.code))
//                {
//                    param.code = "110000";
//                }
//                param.code = param.code.Replace("000", "");
//                string zsql = @" select (select (round(zccount*1.00*100/zcount,2)) zcl from (select count(1) zcount,(select count(1) zccount from zm_pc_yh where create_on BETWEEN @startime and @endtime and fwbh not in (select fwbh From zm_pc_base_cj where fwzt is not null) and fwbh not in (select fwbh From zm_pc_base_sqjz where fwzt is not null and yhly='4')
//) from zm_buildings) tt),zcount,ydb,wdb,dbl dbl from  rysstd_gq_text('','','2024-01-01',now()::timestamp,'zm_pc_base')  ";
//                var data = _dbContext.Database.GetDbConnection().Query<object>(zsql, new {@startime=param.startime,@endtime=param.endtime}).ToList();
//                var res = new RespRet<object>(true, "Ok", data);
//                return res;
//            }
//            catch (Exception ex)
//            {
//                var res = new RespRet<object>(false, ex.ToString(), ex.ToString());
//                WriteSystemLog(usernNumber, "houses/rysstdqkmsg", res);
//                res.Msg = "系统异常";
//                return res;
//            }
//        }













        /// <summary>
        /// 市级-人员疏散通道
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/rysstd")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> Rysstd([FromQuery] string code)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                code = "110000";
            }
            code = code.Replace("000", "");

            string sql = @" ";
            if (code.Length == 3)
            {
                sql = @" select  zcount,(zccount-ydb)wdb,ydb,case when  round(ydb*1.00*100/zccount,2) is null then 0.00 else round(ydb*1.00*100/zccount,2) end   dbl from  (select case when  sum(ssltdbfjsl) is null then 0.00 else  sum(ssltdbfjsl) end ydb ,sum(jbxxgqview.zcount) zcount,sum(zccount) zccount  from  jbxxgqview,zcqkgqview where jbxxgqview.xzqdm=zcqkgqview.xzqdm ) a 	 ";
            }
            if (code.Length == 6)
            {
                sql = @" select  zcount,(zccount-ydb)wdb,ydb,case when  round(ydb*1.00*100/zccount,2) is null then 0.00 else round(ydb*1.00*100/zccount,2) end   dbl from  (select case when  sum(ssltdbfjsl) is null then 0.00 else  sum(ssltdbfjsl) end ydb ,sum(jbxxgqview.zcount) zcount,sum(zccount) zccount  from  jbxxgqview,zcqkgqview where jbxxgqview.xzqdm=zcqkgqview.xzqdm  and jbxxgqview.xzqdm like @code) a 	 ";
            }
            if (code.Length == 9)
            {
                sql = @" select zcount,(zccount-ydb)wdb,ydb,case when  round(ydb*1.00*100/zccount,2) is null then 0.00 else round(ydb*1.00*100/zccount,2) end   dbl from  (select case when  sum(ssltdbfjsl) is null then 0.00 else  sum(ssltdbfjsl) end ydb ,sum(jbxxxzview.zcount) zcount,sum(zccount) zccount  from  jbxxxzview,zcqkxzview where jbxxxzview.towndm=zcqkxzview.towndm and jbxxxzview.towndm like @code) a  
        ";
            }
            if (code.Length == 12)
            {
                sql = @" select zcount,(zccount-ydb)wdb,ydb,case when  round(ydb*1.00*100/zccount,2) is null then 0.00 else round(ydb*1.00*100/zccount,2) end   dbl from  (select case when  sum(ssltdbfjsl) is null then 0.00 else  sum(ssltdbfjsl) end ydb ,sum(jbxxcjview.zcount) zcount,sum(zccount) zccount  from  jbxxcjview,zcqkcjview where jbxxcjview.villagedm=zcqkcjview.villagedm and jbxxcjview.villagedm like @code) a  ";
            }


            var msg = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + code + "%" }).FirstOrDefault();
            return new RespRet<object>(true, "Ok", msg);
        }



        /// <summary>
        /// 窗口护栏拆除
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/hlccqkmsg")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> ckhlccmsg([FromQuery] string code)
        {

            if (string.IsNullOrWhiteSpace(code))
            {
                code = "110000";
            }
            code = code.Replace("000", "");
            string sql = @" ";
            if (code.Length == 3)
            {
                sql = @" 	select zcount,(COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)) sy,case when ckfhwggptzlsl is null then 0.00 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
			case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,sum(ckfhwggptzlsl)ckfhwggptzlsl from  jbxxgqview) a,(select sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cj)  b
			 ";
            }
            if (code.Length == 6)
            {
                sql = @" select zcount,(COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)) sy,case when ckfhwggptzlsl is null then 0.00 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
			case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,sum(ckfhwggptzlsl)ckfhwggptzlsl from  jbxxgqview where xzqdm like @code) a,(select sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cj where xzqdm like  @code)  b ";
            }
            if (code.Length == 9)
            {
                sql = @" select  zcount,(COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)) sy,case when ckfhwggptzlsl is null then 0.00 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0.00 else ccfhwggptzlsl end ccfhwggptzlsl  ,
			case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,sum(ckfhwggptzlsl)ckfhwggptzlsl from  jbxxxzview where towndm like @code) a,(select sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cj where towndm like @code)  b ";
            }
            if (code.Length == 12)
            {
                sql = @" 	select zcount,(COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)) sy,case when ckfhwggptzlsl is null then 0.00 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0.00 else ccfhwggptzlsl end ccfhwggptzlsl  ,
			case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,sum(ckfhwggptzlsl)ckfhwggptzlsl from  jbxxcjview where villagedm like @code) a,(select sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cj where villagedm like @code)  b ";
            }
            var msg = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + code + "%" }).FirstOrDefault();
            return new RespRet<object>(true, "Ok", msg);
        }



        /// <summary>
        /// 固定警示标牌
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/gdjsbt")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> gdjsbt([FromQuery] string code)
        {
            var usernNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(c => c.Number == usernNumber);
            var a = JsonRegion(user.District);
            JObject obj = JObject.Parse(user.District);
            string RegionCode = (string)obj["RegionCode"];
            RegionCode = RegionCode.Replace("000", "");
            if (string.IsNullOrWhiteSpace(code))
            {
                code = RegionCode;
            }
            code = code.Replace("000", "");

            string tbsql = @$" ";
            string sql = @" ";
            if (code.Length == 3)
            {
                tbsql = @$" select sum(xggdjsbp) xggdjsbp,case when  round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2) is null then 0.00 when round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2)>100 then 100.00 else round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2) end  azl  from  jbxxgqview  ";
            }
            if (code.Length == 6)
            {
                tbsql = @$" select sum(xggdjsbp) xggdjsbp,case when  round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2) is null then 0.00 when round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2)>100 then 100.00 else round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2) end  azl from  jbxxgqview where xzqdm like @code	 ";
            }

            if (code.Length == 9)
            {
                tbsql = @$" select sum(xggdjsbp) xggdjsbp,case when  round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2) is null then 0.00 when round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2)>100 then 100.00 else round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2) end  azl from  jbxxxzview  where towndm like @code
 ";
            }
            if (code.Length == 12)
            {
                tbsql = @$" select sum(xggdjsbp) xggdjsbp,case when  round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2) is null then 0.00 when round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2)>100 then 100.00 else round(sum(xggdjsbp)*1.00*100/sum(jzfjs),2) end  azl from  jbxxcjview  where villagedm like @code ";
            }


            var tb = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + code + "%" }).ToList();
            var msg = _dbContext.Database.GetDbConnection().Query<object>(tbsql, new { @code = "%" + code + "%" }).FirstOrDefault();
            return new RespRet<object>(true, "Ok", new { tb = tb, msg = msg });
        }




        /// <summary>
        /// 电动自行车违规充电
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/ddzxcwgcdmsg")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> ddzxcwgcdmsg([FromQuery] string code)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                code = "110000";
            }
            code = code.Replace("000", "");
            //if (!code.Contains(RegionCode))
            //{
            //    var error = new RespRet<object>(false, "未在管辖范围内");
            //    WriteSystemLog("housescj/ddzxcwgcdmsg", error, null);
            //    return error;
            //}
            string sql = @$" select  (select sum(bdfwjzrydddzxcsl) bdfwjzrydddzxcsl from jbxxgqview ),sum(fx)zs ,sum(zg)qlddcsl, case when  round(sum(zg)*100*1.00/sum(fx),2) is null then 0.00 when round(sum(zg)*100*1.00/sum(fx),2)>100 then 100.00 else  round(sum(zg)*100*1.00/sum(fx),2) end wcl  from  (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,a.xzqdm from  zcyhgqview a,jcyhgqview b where a.xzqdm=b.xzqdm)t1 join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,a.xzqdm from  (select sum(zg_ddc_num) zc,b.xzqdm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where  a.create_on<(case when c.fwzt is not null and yhly='5' then c.create_on else now() end)  GROUP BY b.xzqdm) a full join (select sum(zg_ddc_num) jc,b.xzqdm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5'  GROUP BY b.xzqdm)b on a.xzqdm=b.xzqdm) t2 on t1.xzqdm=t2.xzqdm    ";
            code = code.Replace("000", "");
            var lea = code.Replace("000", "").Length;
            if (lea == 6)
            {
                sql = @$" select  (select sum(bdfwjzrydddzxcsl) bdfwjzrydddzxcsl from jbxxgqview where xzqdm like @code   ),sum(fx)zs ,sum(zg)qlddcsl, case when  round(sum(zg)*100*1.00/sum(fx),2) is null then 0.00 when round(sum(zg)*100*1.00/sum(fx),2)>100 then 100.00 else  round(sum(zg)*100*1.00/sum(fx),2) end wcl  from  (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,a.xzqdm from  zcyhgqview a,jcyhgqview b where a.xzqdm=b.xzqdm)t1 join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,a.xzqdm from  (select sum(zg_ddc_num) zc,b.xzqdm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where  a.create_on<(case when c.fwzt is not null and yhly='5' then c.create_on else now() end)  GROUP BY b.xzqdm) a full join (select sum(zg_ddc_num) jc,b.xzqdm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5'  GROUP BY b.xzqdm)b on a.xzqdm=b.xzqdm) t2 on t1.xzqdm=t2.xzqdm   where t1.xzqdm like @code  ";
            }
            if (lea == 9)
            {
                sql = @$" select  (select sum(bdfwjzrydddzxcsl) bdfwjzrydddzxcsl from jbxxxzview where towndm like @code),sum(fx)zs ,sum(zg)qlddcsl, case when  round(sum(zg)*100*1.00/sum(fx),2) is null then 0.00 when round(sum(zg)*100*1.00/sum(fx),2)>100 then 100.00 else  round(sum(zg)*100*1.00/sum(fx),2) end wcl  from  (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,a.towndm from  zcyhxzview a,jcyhxzview b where a.towndm=b.towndm)t1 join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,a.towndm from  (select sum(zg_ddc_num) zc,b.towndm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where  a.create_on<(case when c.fwzt is not null and yhly='5' then c.create_on else now() end)  GROUP BY b.towndm) a full join (select sum(zg_ddc_num) jc,b.towndm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5'  GROUP BY b.towndm)b on a.towndm=b.towndm) t2 on t1.towndm=t2.towndm  where t1.towndm like @code ";
            }
            if (lea == 12)
            {
                sql = @$" select  (select sum(bdfwjzrydddzxcsl) bdfwjzrydddzxcsl from jbxxcjview where villagedm like @code),sum(fx)zs ,sum(zg)qlddcsl, case when  round(sum(zg)*100*1.00/sum(fx),2) is null then 0.00 when round(sum(zg)*100*1.00/sum(fx),2)>100 then 100.00 else  round(sum(zg)*100*1.00/sum(fx),2) end wcl  from  (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,a.villagedm from  zcyhcjview a,jcyhcjview b where a.villagedm=b.villagedm)t1 join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,a.villagedm from  (select sum(zg_ddc_num) zc,b.villagedm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where  a.create_on<(case when c.fwzt is not null and yhly='5' then c.create_on else now() end)  GROUP BY b.villagedm) a full join (select sum(zg_ddc_num) jc,b.villagedm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5'  GROUP BY b.villagedm)b on a.villagedm=b.villagedm) t2 on t1.villagedm=t2.villagedm  where t1.villagedm like @code ";
            }
            var msg = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + code + "%" }).FirstOrDefault();
            return new RespRet<object>(true, "Ok", msg);
        }




        /// <summary>
        /// 电动自行车违规情况  二级页面下钻
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/ddzxcwgqktable")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> ddzxcwgqktable([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null)
                {
                    return new RespRet<object>(false, "参数不能为空");
                }
                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                param.startime = DateTime.Now.AddYears(-100);
                param.endtime = DateTime.Now.AddHours(23);
                param.endtime = DateTime.Now.AddMinutes(59);
                param.endtime = DateTime.Now.AddSeconds(59);
                param.code = param.code.Replace("000", "");
                string formattedDate = param.endtime.ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + DateTime.Now.Date.Year;
                string sql = @$" select bdfwjzrydddzxcsl, t3.xzqdm code,t3.xzq name,COALESCE(fx,0) zs ,COALESCE(zg,0)qlddcsl, case when  round(zg*100*1.00/case when 	fx=0 then null else fx end,2) is null then 0.00 when round(zg*100*1.00/case when 	fx=0 then null else fx end,2)>100 then 100.00 else  round(zg*100*1.00/case when 	fx=0 then null else fx end,2) end wcl  from  (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,a.xzqdm from  zcyhgqtext(@startime,@endtime::TIMESTAMP,@tablename) a,jcyhgqtext(@startime,@endtime::TIMESTAMP,@tablename) b where a.xzqdm=b.xzqdm)t1 join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,a.xzqdm from  (select sum(zg_ddc_num) zc,b.xzqdm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh  where a.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           ) and  a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.xzqdm) a full join (select sum(zg_ddc_num) jc,b.xzqdm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5' and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.xzqdm)b on a.xzqdm=b.xzqdm) t2 on t1.xzqdm=t2.xzqdm  RIGHT JOIN  (SELECT t1.xzqdm,t1.xzq,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
            zm_buildings.xzq,
            zm_buildings.xzqdm
           FROM zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_buildings.xzqdm, zm_buildings.xzq
          ORDER BY zm_buildings.xzqdm) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE ((zm_pc_base.village)::text IN ( SELECT zm_buildings.villagedm
                   FROM zm_buildings))   and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_pc_base.xzqdm, zm_pc_base.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text))) left join (select t1.xzqdm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1  where t1.create_on between @startime and @endtime::TIMESTAMP and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           ) GROUP BY t1.xzqdm) t3 on t2.xzqdm=t3.xzqdm
  ORDER BY t1.xzqdm) t3 on t3.xzqdm=t2.xzqdm ORDER BY t3.xzqdm ";
                param.code = param.code.Substring(param.code.Length - 3) == "000" ? param.code.Substring(0, param.code.Length - 3) : param.code;
                var lea = param.code.Substring(param.code.Length - 3) == "000" ? param.code.Length - 3 : param.code.Length;
                if (lea == 6 )
                {
                    sql = @$" select t3.xzqdm,t3.xzq,bdfwjzrydddzxcsl, t3.towndm code,t3.town name,COALESCE(fx,0) zs ,COALESCE(zg,0)qlddcsl, case when  round(zg*100*1.00/case when 	fx=0 then null else fx end,2) is null then 0.00 when round(zg*100*1.00/case when 	fx=0 then null else fx end,2)>100 then 100.00 else  round(zg*100*1.00/case when 	fx=0 then null else fx end,2) end wcl  from  (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,COALESCE(a.towndm,b.towndm) towndm from  zcyhxztext(@startime,@endtime::TIMESTAMP,@tablename) a,jcyhxztext(@startime,@endtime::TIMESTAMP,@tablename) b where a.towndm=b.towndm)t1 full join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,COALESCE(a.towndm,b.towndm) towndm from  (select sum(zg_ddc_num) zc, b.towndm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh  where  a.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           ) and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.towndm) a full join (select sum(zg_ddc_num) jc,b.towndm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5' and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.towndm)b on a.towndm=b.towndm) t2 on t1.towndm=t2.towndm
right join (	select bdfwjzrydddzxcsl,xzq,xzqdm, towndm,town from ( SELECT t1.towndm,t1.town,xzq,xzqdm,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
	  max(zm_buildings.xzq) xzq,
		 max(zm_buildings.xzqdm) xzqdm,
           max(zm_buildings.town) town,
            zm_buildings.towndm
           FROM zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_buildings.towndm
          ORDER BY zm_buildings.towndm) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.town
           FROM (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE ((zm_pc_base.village)::text IN ( SELECT zm_buildings.villagedm
                   FROM zm_buildings))   and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_pc_base.town) t2 ON (((t1.towndm)::text = (t2.town)::text))) left join (select t1.towndm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1  where t1.create_on between @startime and @endtime::TIMESTAMP and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           ) GROUP BY t1.towndm) t3 on t1.towndm=t3.towndm)a ) t3 on t1.towndm=t3.towndm
where t3.towndm like @code ";
                }
                if (lea == 9)
                {
                    sql = @$" select  towndm,town,xzqdm,xzq,bdfwjzrydddzxcsl, t3.villagedm code,t3.village name,COALESCE(fx,0) zs ,COALESCE(zg,0)qlddcsl, case when  round(zg*100*1.00/case when 	fx=0 then null else fx end,2) is null then 0.00 when round(zg*100*1.00/case when 	fx=0 then null else fx end,2)>100 then 100.00 else  round(zg*100*1.00/case when 	fx=0 then null else fx end,2) end wcl  from (select COALESCE(fx,0) fx,COALESCE(zg,0)zg,COALESCE(t1.villagedm,t2.villagedm) villagedm from (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,a.villagedm from  zcyhcjtext(@startime,@endtime::TIMESTAMP,@tablename) a,jcyhcjtext(@startime,@endtime::TIMESTAMP,@tablename) b where a.villagedm=b.villagedm)t1 full join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,COALESCE(a.villagedm,b.villagedm) villagedm from  (select sum(zg_ddc_num) zc,b.villagedm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh  where  a.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           ) and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.villagedm) a full join (select sum(zg_ddc_num) jc,b.villagedm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5' and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.villagedm)b on a.villagedm=b.villagedm) t2 on t1.villagedm=t2.villagedm)t2 
right join 
(SELECT t1.villagedm,t1.village,t1.towndm,t1.town,t1.xzq,t1.xzqdm,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
           max(zm_buildings.village)village,
					 max(zm_buildings.towndm) towndm,
					 max(zm_buildings.town)town,
					 max(zm_buildings.xzqdm)xzqdm,
					 max(zm_buildings.xzq)xzq,
            zm_buildings.villagedm
           FROM zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_buildings.villagedm
          ) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.village
           FROM (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE ((zm_pc_base.village)::text IN ( SELECT zm_buildings.villagedm
                   FROM zm_buildings))   and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_pc_base.village) t2 ON (((t1.villagedm)::text = (t2.village)::text))) left join (select t1.villagedm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1  where t1.create_on between @startime and @endtime::TIMESTAMP and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )  GROUP BY t1.villagedm) t3 on t1.villagedm=t3.villagedm) t3 on t3.villagedm=t2.villagedm
where t3.villagedm like @code ";
                }
                if (lea == 12)
                {
                    sql = @$" select  towndm,town,xzqdm,xzq,bdfwjzrydddzxcsl, t3.villagedm code,t3.village name,COALESCE(fx,0) zs ,COALESCE(zg,0)qlddcsl, case when  round(zg*100*1.00/case when 	fx=0 then null else fx end,2) is null then 0.00 when round(zg*100*1.00/case when 	fx=0 then null else fx end,2)>100 then 100.00 else  round(zg*100*1.00/case when 	fx=0 then null else fx end,2) end wcl  from (select COALESCE(fx,0) fx,COALESCE(zg,0)zg,COALESCE(t1.villagedm,t2.villagedm) villagedm from (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,a.villagedm from  zcyhcjtext(@startime,@endtime::TIMESTAMP,@tablename) a,jcyhcjtext(@startime,@endtime::TIMESTAMP,@tablename) b where a.villagedm=b.villagedm)t1 full join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,COALESCE(a.villagedm,b.villagedm) villagedm from  (select sum(zg_ddc_num) zc,b.villagedm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh  where  a.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           ) and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.villagedm) a full join (select sum(zg_ddc_num) jc,b.villagedm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5' and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.villagedm)b on a.villagedm=b.villagedm) t2 on t1.villagedm=t2.villagedm)t2 
right join 
(SELECT t1.villagedm,t1.village,t1.towndm,t1.town,t1.xzq,t1.xzqdm,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
           max(zm_buildings.village)village,
					 max(zm_buildings.towndm) towndm,
					 max(zm_buildings.town)town,
					 max(zm_buildings.xzqdm)xzqdm,
					 max(zm_buildings.xzq)xzq,
            zm_buildings.villagedm
           FROM zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_buildings.villagedm
          ) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.village
           FROM (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE ((zm_pc_base.village)::text IN ( SELECT zm_buildings.villagedm
                   FROM zm_buildings))   and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_pc_base.village) t2 ON (((t1.villagedm)::text = (t2.village)::text))) left join (select t1.villagedm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1  where t1.create_on between @startime and @endtime::TIMESTAMP and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )  GROUP BY t1.villagedm) t3 on t1.villagedm=t3.villagedm) t3 on t3.villagedm=t2.villagedm
where t3.villagedm like @code ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @tablename = table_name, @code = "%" + param.code + "%", @startime = param.startime, @endtime = formattedDate }).ToList();

                var res = new RespRet<object>(true, "Ok", data);
                ///*WriteSystemLog*/(usernNumber, "houses/ddzxcwgqktable", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/ddzxcwgqktable", res);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 清理液化石油气情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/qlyhsyqqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> qlyhsyqqk([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null)
                {
                    return new RespRet<object>(false, "参数不能为空");
                }
                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                param.code = param.code.Replace("000", "");
                string sql = @" ";
                if (param.code.Length == 3)
                {
                    sql = @$" select fx value , '发现石油液化气房屋栋数' name From (select sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhgqview a,jcyhgqview b where a.xzqdm=b.xzqdm)a,(select  COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end)) a,  (select sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh ) b)b
	union all
select zg value, '清理石油液化气数量' name From (select sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhgqview a,jcyhgqview b where a.xzqdm=b.xzqdm)a,(select  COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end)) a,  (select sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh ) b)b
		";
                }
                if (param.code.Length == 6)
                {
                    sql = @" select fx value , '发现石油液化气房屋栋数' name From (select sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhgqview a,jcyhgqview b where a.xzqdm=b.xzqdm and a.xzqdm like @code)a,(select  COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) and b.xzqdm like @code) a,  (select sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh and b.xzqdm like @code ) b)b  
	union all
select zg value, '清理石油液化气数量' From (select sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhgqview a,jcyhgqview b where a.xzqdm=b.xzqdm and a.xzqdm like @code)a,(select  COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) and b.xzqdm like @code) a,  (select sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh and b.xzqdm like @code ) b)b  
	";
                }
                if (param.code.Length == 9)
                {
                    sql = @"  select fx value , '发现石油液化气房屋栋数' name From (select sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhxzview a,jcyhxzview b where a.towndm=b.towndm and a.towndm like @code)a,(select  COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) and b.towndm like @code) a,  (select sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh and b.towndm like @code ) b)b 
	union all
select zg value, '清理石油液化气数量' From (select sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhxzview a,jcyhxzview b where a.towndm=b.towndm and a.towndm like @code)a,(select  COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) and b.towndm like @code) a,  (select sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh and b.towndm like @code ) b)b 
	";
                }
                if (param.code.Length == 12)
                {
                    sql = @"  select fx value , '发现石油液化气房屋栋数' name From (select sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhcjview a,jcyhcjview b where a.villagedm=b.villagedm and a.villagedm like @code)a,(select  COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) and b.villagedm like @code) a,  (select sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh and b.villagedm like @code ) b)b
	union all
select zg value, '清理石油液化气数量' From (select sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhcjview a,jcyhcjview b where a.villagedm=b.villagedm and a.villagedm like @code)a,(select  COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh left join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) and b.villagedm like @code) a,  (select sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh and b.villagedm like @code ) b)b
	";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + param.code + "%" }).ToList();

                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/qlyhsyqqk", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/qlyhsyqqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 清理液化石油气情况二级页面
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/qlyhsyqqktable")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> qlyhsyqqktable([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null)
                {
                    return new RespRet<object>(false, "参数不能为空");
                }
                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                param.code = param.code.Replace("000", "");
                string sql = @" ";
                if (param.code.Length == 3)
                {
                    sql = @$"  select a.xzqdm,a.xzq,case when fx is null then 0 else fx end fx,case when zg is null then 0 else zg end zg,case when fx=0 then 0.00||'%' else (case when round(zg*1.00*100/fx,2) is null then 0.00||'%' when round(zg*1.00*100/fx,2)>100 then 100.00||'%' else round(zg*1.00*100/fx,2)||'%' end ) end zgl,case when fx=0 then 0.00 else (case when round(zg*1.00*100/fx,2) is null then 0.00 when round(zg*1.00*100/fx,2)>100 then 100.00 else round(zg*1.00*100/fx,2) end ) end value  from  (select a.xzqdm,max(a.xzq) xzq,sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhgqview a,jcyhgqview b where a.xzqdm=b.xzqdm GROUP BY a.xzqdm)a left join (select  a.xzqdm,COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select b.xzqdm,max(b.xzq) xzq,sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh full join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) GROUP BY  b.xzqdm) a left join (select b.xzqdm,sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh GROUP BY b.xzqdm ) b on a.xzqdm=b.xzqdm)b on a.xzqdm=b.xzqdm 
           ";
                }
                if (param.code.Length == 6)
                {
                    sql = @" select a.towndm,a.xzqdm ,a.town,a.xzq,case when fx is null then 0 else fx end fx,case when zg is null then 0 else zg end zg,case when fx=0 then 0.00||'%' else (case when round(zg*1.00*100/fx,2) is null then 0.00||'%' when round(zg*1.00*100/fx,2)>100 then 100.00||'%' else round(zg*1.00*100/fx,2)||'%' end ) end zgl,case when fx=0 then 0.00 else (case when round(zg*1.00*100/fx,2) is null then 0.00 when round(zg*1.00*100/fx,2)>100 then 100.00 else round(zg*1.00*100/fx,2) end ) end value  from  (select max(a.town) town,max(a.xzqdm)xzqdm,a.towndm,max(a.xzq) xzq,sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhxzview a,jcyhxzview b where a.towndm=b.towndm GROUP BY a.towndm)a left join (select  a.towndm,COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select b.towndm,max(b.xzq) xzq,sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh full join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) GROUP BY  b.towndm) a left join (select b.towndm,sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh GROUP BY b.towndm ) b on a.towndm=b.towndm)b on a.towndm=b.towndm where a.towndm like @code ";
                }
                if (param.code.Length == 9)
                {
                    sql = @" select a.town,a.towndm,a.villagedm,a.xzqdm ,a.village,a.xzq,case when fx is null then 0 else fx end fx,case when zg is null then 0 else zg end zg,case when fx=0 then 0.00||'%' else (case when round(zg*1.00*100/fx,2) is null then 0.00||'%' when round(zg*1.00*100/fx,2)>100 then 100.00||'%' else round(zg*1.00*100/fx,2)||'%' end ) end zgl,case when fx=0 then 0.00 else (case when round(zg*1.00*100/fx,2) is null then 0.00 when round(zg*1.00*100/fx,2)>100 then 100.00 else round(zg*1.00*100/fx,2) end ) end value  from  (select max(a.town)town,max(a.towndm) towndm,max(a.village) village,max(a.xzqdm)xzqdm,a.villagedm,max(a.xzq) xzq,sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhcjview a,jcyhcjview b where a.villagedm=b.villagedm GROUP BY a.villagedm)a left join (select  a.villagedm,COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select b.villagedm,max(b.xzq) xzq,sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh full join zm_pc_base_cj c on b.fwbh=c.fwbh where c.yhly=5 and a.create_on<(case when c.fwzt is not null then c.create_on else now() end) GROUP BY  b.villagedm) a left join (select b.villagedm,sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh GROUP BY b.villagedm ) b on a.villagedm=b.villagedm)b on a.villagedm=b.villagedm  where a.villagedm like @code ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + param.code + "%" }).ToList();

                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/qlyhsyqqktable", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/qlyhsyqqktable", res);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 电动自行车违规情况 柱状图
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/ddzxcwgqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> ddzxcwgqk([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {

                if (param == null)
                {
                    return new RespRet<object>(false, "参数不能为空");
                }
                string time = DateTime.Today
.AddHours(23)
.AddMinutes(59)
.AddSeconds(59)
.ToString("yyyy-MM-dd HH:mm:ss");

                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                param.code = param.code.Replace("000", "");
                string sql = $@" 	
	select CONCAT('[', STRING_AGG(CAST( replace(xzq, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(t1.xzqdm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(zg AS VARCHAR), ', ' ), ']') zg,CONCAT('[', STRING_AGG(CAST(zg AS VARCHAR), ', ' ), ']') fx from (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,a.xzqdm,a.xzq from  (select sum(zg_ddc_num) zc,b.xzqdm,max(b.xzq)xzq from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh  where  b.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )    GROUP BY b.xzqdm) a full join (select sum(zg_ddc_num) jc,b.xzqdm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5'   GROUP BY b.xzqdm)b on a.xzqdm=b.xzqdm) t1
	 ";

                if (param.code.Length == 6)
                {
                    sql = $@" 	
	
select CONCAT('[', STRING_AGG(CAST( replace(town, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(a.towndm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(fx AS VARCHAR), ', ' ), ']') fx,CONCAT('[', STRING_AGG(CAST(zg AS VARCHAR), ', ' ), ']') zg  from  (select max(a.town) town,max(a.xzqdm)xzqdm,a.towndm,max(a.xzq) xzq,sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhxzview a,jcyhxzview b where a.towndm=b.towndm GROUP BY a.towndm)a left join (select  a.towndm,COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select b.towndm,max(b.xzq) xzq,sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh   where a.fwbh not in 	
	(
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )  GROUP BY  b.towndm) a left join (select b.towndm,sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh and b.fwbh not in 	
	(
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           ) GROUP BY b.towndm ) b on a.towndm=b.towndm)b on a.towndm=b.towndm where a.towndm like @code
	 ";
                }
                if (param.code.Length == 9)
                {
                    sql =$@" 					 select CONCAT('[', STRING_AGG(CAST( replace(village, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(a.villagedm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(fx AS VARCHAR), ', ' ), ']') fx,CONCAT('[', STRING_AGG(CAST(zg AS VARCHAR), ', ' ), ']') zg  from  (select max(a.town)town,max(a.towndm) towndm,max(a.village) village,max(a.xzqdm)xzqdm,a.villagedm,max(a.xzq) xzq,sum( case when (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas)=0 then null else (a.use_bottled_liquefied_gas+b.use_bottled_liquefied_gas) end) fx from  zcyhcjview a,jcyhcjview b where a.villagedm=b.villagedm GROUP BY a.villagedm)a left join (select  a.villagedm,COALESCE(zc,0)+  COALESCE(jc,0) zg from  (select b.villagedm,max(b.xzq) xzq,sum(zg_yhsyq_num) zc from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh full join zm_pc_base_cj c on b.fwbh=c.fwbh where  b.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           ) and c.yhly=5  GROUP BY  b.villagedm) a left join (select b.villagedm,sum(zg_yhsyq_num) jc from zm_pc_yhlog_dxzgson_cj a,zm_buildings b,zm_pc_yhlog_dx_cj c where  c.jcly=5 and c.id=a.yhlog_dx_id and a.fwbh=b.fwbh GROUP BY b.villagedm ) b on a.villagedm=b.villagedm)b on a.villagedm=b.villagedm  where a.villagedm like @code ";
                }

                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new {@endtime=time, @code = "%" + param.code + "%" }).FirstOrDefault();
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (data != null)
                {
                    var properties = data as IDictionary<string, object>;
                    foreach (var kvp in properties)
                    {
                        var stringlist = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        var list = new List<string>();
                        foreach (var item in stringlist)
                        {
                            list.Add(item);
                        }
                        dictionary.Add(kvp.Key, list);
                    }
                    var r = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/ddzxcwgqk", r);
                    return r;
                }
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/ddzxcwgqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }




        /// <summary>
        /// 电动自行车违规情况 柱状图
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/ddzxcwgqkmsg")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> ddzxcwgqkmsg([FromBody] DateQuery param)
        {



            string time = DateTime.Today
 .AddHours(23)
 .AddMinutes(59)
 .AddSeconds(59)
 .ToString("yyyy-MM-dd HH:mm:ss");
            DateTime startTime = DateTime.ParseExact(
    "2024-01-01",
    "yyyy-MM-dd",
    CultureInfo.InvariantCulture);

            string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
            try
            {
                string sql = $@"  select  (select sum(bdfwjzrydddzxcsl) bdfwjzrydddzxcsl from (   SELECT t1.xzqdm,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
            zm_buildings.xzq,
            zm_buildings.xzqdm
           FROM  zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_buildings.xzqdm, zm_buildings.xzq
          ORDER BY zm_buildings.xzqdm) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE ((zm_pc_base.village)::text IN ( SELECT zm_buildings.villagedm
                   FROM zm_buildings))   and fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime
           )
          GROUP BY zm_pc_base.xzqdm, zm_pc_base.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text))) left join (select t1.xzqdm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1  where t1.create_on between @startime and @endtime::TIMESTAMP and fwbh not in ( SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime) GROUP BY t1.xzqdm) t3 on t2.xzqdm=t3.xzqdm
  ORDER BY t1.xzqdm)a),COALESCE(sum(fx),0)zs ,COALESCE(sum(zg),0)zg, case when  round(sum(zg)*100*1.00/case when 	sum(fx)=0 then null else sum(fx) end,2) is null then 0.00 when round(sum(zg)*100*1.00/case when 	sum(fx)=0 then null else sum(fx) end,2)>100 then 100.00 else  round(sum(zg)*100*1.00/case when 	sum(fx)=0 then null else sum(fx) end,2) end wcl  from  (select a.xzq xzq, a.use_electric_bicycle+b.use_electric_bicycle fx,a.xzqdm from  zcyhgqtext(@startime,@endtime::TIMESTAMP,@tablename) a,jcyhgqtext(@startime,@endtime::TIMESTAMP,@tablename) b where a.xzqdm=b.xzqdm)t1 join (select  (case when zc is null then 0 else zc end+ case when jc is null then 0 else jc end) zg,a.xzqdm from  (select sum(zg_ddc_num) zc,b.xzqdm from zm_pc_yhlog_dxzgson a join zm_buildings b on a.fwbh=b.fwbh where a.fwbh not in (SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@endtime) and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.xzqdm) a full join (select sum(zg_ddc_num) jc,b.xzqdm from zm_pc_yhlog_dxzgson_cj a join zm_buildings b on a.fwbh=b.fwbh  join zm_pc_yhlog_dx_cj c on a.yhlog_dx_id=c.id join zm_pc_yh_cj d on d.id=c.yhlog_id  where d.jcly='5' and a.create_on between @startime and @endtime::TIMESTAMP  GROUP BY b.xzqdm)b on a.xzqdm=b.xzqdm) t2 on t1.xzqdm=t2.xzqdm     "; 
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new {@tablename=table_name,@endtime=time,@startime=startTime, @code = "%" + param.code + "%" }).FirstOrDefault();
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/ddzxcwgqkmsg", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(null, "houses/ddzxcwgqkmsg", res);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 护栏拆除情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/hlccqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> ckhlccbar([FromBody] DateQuery param)
        {

            if (param == null)
            {
                return new RespRet<object>(false, "参数不能为空");
            }
            if (string.IsNullOrWhiteSpace(param.code))
            {
                param.code = "110000";
            }
            param.code = param.code.Replace("000", "");

            string sql = @" ";
            string endtime = DateTime.Today
     .AddHours(23)
     .AddMinutes(59)
     .AddSeconds(59)
     .ToString("yyyy-MM-dd HH:mm:ss");

            string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
            #region
            if (param.code.Length == 3)
            {
                sql = $@" select ckfhwggptzlsl,case when  ((COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)))>0 then ((COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0))) else 0 end  sy,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name xzq , code xzqdm,CASE WHEN ccl > 100 THEN 100.00||'%' when ckfhwggptzlsl=0 then 0.00||'%'  when ccl is null then 0.00||'%' ELSE ccl||'%' END  ccl from (	select  zcount,code,name,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select sum(zcount)zcount,xzqdm code,max(xzq) name, case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  (SELECT t1.xzq,
    t1.xzqdm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (( SELECT count(1) AS zcount,
            zm_buildings.xzq,
            zm_buildings.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""其它""
           FROM zm_buildings
          WHERE (NOT ((zm_buildings.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_buildings.xzqdm, zm_buildings.xzq) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_on,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_pc_base.xzqdm, zm_pc_base.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text)))
  ORDER BY t1.xzqdm)jbxxgqview GROUP BY xzqdm) a left join (select xzqdm,sum(ccfhwggptzlsl) ccfhwggptzlsl From 	(select xzqdm,xzq,towndm,town,ckfhwggptzlsl zcount,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name , code  from (				
		select xzqdm,xzq,towndm,town,zcount, code,name,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,max(xzqdm)xzqdm,max(xzq)xzq,max(towndm)towndm,max(town)town,villagedm code,max(village) name,case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  (SELECT t4.region_name AS village,
    t1.villagedm,
    t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (((( SELECT count(1) AS zcount,
            mm.villagedm,
            mm.xzq,
            mm.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""其它"",
            mm.towndm
           FROM zm_buildings mm
          WHERE (NOT ((mm.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text =@endtime::text)))))
          GROUP BY mm.villagedm, mm.xzq, mm.xzqdm, mm.towndm
          ORDER BY mm.villagedm) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.village,
            zm_pc_base.town,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_by,
                    t1_1.create_on,
                    t1_1.create_ip,
                    t1_1.modified_by,
                    t1_1.modified_on,
                    t1_1.modified_ip,
                    t1_1.is_delete,
                    t1_1.delete_by,
                    t1_1.delete_on,
                    t1_1.delete_ip,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime)))))
          GROUP BY zm_pc_base.village, zm_pc_base.town, zm_pc_base.xzq, zm_pc_base.xzqdm) t2 ON (((t1.villagedm)::text = (t2.village)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
     LEFT JOIN zm_department t4 ON (((t1.villagedm)::text = (t4.id)::text)))
  ORDER BY t1.villagedm)jbxxcjview  group by villagedm) a left join  (select villagedm,sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cjlog where  create_on between  @startime and @endtime::TIMESTAMP group by villagedm)  b on a.code=b.villagedm )a ORDER BY ccl desc,code
) a   group by xzqdm)  b	 on a.code=b.xzqdm)a ORDER BY ccl desc,code  
       ";
            }
            if (param.code.Length == 6)
            {
                sql = $@" select ckfhwggptzlsl ,case when  ((COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)))>0 then ((COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0))) else 0 end  sy,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl  ,name town , code towndm,xzq,xzqdm,CASE WHEN ccl > 100 THEN 100.00||'%' when ckfhwggptzlsl=0 then 0.00||'%'  when ccl is null then 0.00||'%' ELSE ccl||'%' END ccl from (				
		select   zcount,code,name,xzqdm,xzq,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,towndm code,max(town) name,max(xzq) xzq,max(xzqdm) xzqdm,case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  (SELECT t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM ((( SELECT count(1) AS zcount,
            zm_buildings.towndm,
            zm_buildings.xzq,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""其它"",
            zm_buildings.xzqdm
           FROM zm_buildings
          WHERE (NOT ((zm_buildings.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_buildings.towndm, zm_buildings.xzq, zm_buildings.xzqdm
          ORDER BY zm_buildings.towndm) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.town
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_by,
                    t1_1.create_on,
                    t1_1.create_ip,
                    t1_1.modified_by,
                    t1_1.modified_on,
                    t1_1.modified_ip,
                    t1_1.is_delete,
                    t1_1.delete_by,
                    t1_1.delete_on,
                    t1_1.delete_ip,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs,
                    t2_1.fwzt
                   FROM (zm_pc_base t1_1
                     LEFT JOIN zm_pc_base_cj t2_1 ON (((t1_1.fwbh)::text = (t2_1.fwbh)::text)))) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_pc_base.town) t2 ON (((t1.towndm)::text = (t2.town)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
  ORDER BY t1.towndm)jbxxxzview where towndm like @code group by towndm) a left join  (select towndm,sum(ccfhwggptzlsl) ccfhwggptzlsl From 	(select xzqdm,xzq,towndm,town,ckfhwggptzlsl zcount,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name , code  from (				
		select xzqdm,xzq,towndm,town,zcount, code,name,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,max(xzqdm)xzqdm,max(xzq)xzq,max(towndm)towndm,max(town)town,villagedm code,max(village) name,case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  (SELECT t4.region_name AS village,
    t1.villagedm,
    t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (((( SELECT count(1) AS zcount,
            mm.villagedm,
            mm.xzq,
            mm.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""其它"",
            mm.towndm
           FROM zm_buildings mm
          WHERE (NOT ((mm.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY mm.villagedm, mm.xzq, mm.xzqdm, mm.towndm
          ORDER BY mm.villagedm) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.village,
            zm_pc_base.town,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_by,
                    t1_1.create_on,
                    t1_1.create_ip,
                    t1_1.modified_by,
                    t1_1.modified_on,
                    t1_1.modified_ip,
                    t1_1.is_delete,
                    t1_1.delete_by,
                    t1_1.delete_on,
                    t1_1.delete_ip,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_pc_base.village, zm_pc_base.town, zm_pc_base.xzq, zm_pc_base.xzqdm) t2 ON (((t1.villagedm)::text = (t2.village)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
     LEFT JOIN zm_department t4 ON (((t1.villagedm)::text = (t4.id)::text)))
  ORDER BY t1.villagedm)jbxxcjview  group by villagedm) a left join  (select villagedm,sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cjlog where  create_on between  @startime and @endtime::TIMESTAMP group by villagedm)  b on a.code=b.villagedm )a ORDER BY ccl desc,code
) a   group by towndm )  b on a.code=b.towndm )a ORDER BY ccl desc,code

	";
            }

            if (param.code.Length == 9)
            {
                sql = $@" select ckfhwggptzlsl ,case when  ((COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)))>0 then ((COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0))) else 0 end  sy,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name village  , code villagedm,towndm,town,xzqdm,xzq,CASE WHEN ccl > 100 THEN 100.00||'%' when ckfhwggptzlsl=0 then 0.00||'%'  when ccl is null then 0.00||'%' ELSE ccl||'%' END  ccl from (				
		select  zcount, code,name,xzq,xzqdm,town,towndm,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,villagedm code,max(village) name,max(towndm) towndm,max(town) town,max(xzq) xzq,max(xzqdm) xzqdm,case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  (SELECT t4.region_name AS village,
    t1.villagedm,
    t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (((( SELECT count(1) AS zcount,
            mm.villagedm,
            mm.xzq,
            mm.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""其它"",
            mm.towndm
           FROM zm_buildings mm
          WHERE (NOT ((mm.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY mm.villagedm, mm.xzq, mm.xzqdm, mm.towndm
          ORDER BY mm.villagedm) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.village,
            zm_pc_base.town,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_by,
                    t1_1.create_on,
                    t1_1.create_ip,
                    t1_1.modified_by,
                    t1_1.modified_on,
                    t1_1.modified_ip,
                    t1_1.is_delete,
                    t1_1.delete_by,
                    t1_1.delete_on,
                    t1_1.delete_ip,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_pc_base.village, zm_pc_base.town, zm_pc_base.xzq, zm_pc_base.xzqdm) t2 ON (((t1.villagedm)::text = (t2.village)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
     LEFT JOIN zm_department t4 ON (((t1.villagedm)::text = (t4.id)::text)))
  ORDER BY t1.villagedm)jbxxcjview where villagedm like @code group by villagedm) a left join  (select villagedm,sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cjlog where villagedm like @code and create_on between  @startime and @endtime::TIMESTAMP group by villagedm)  b on a.code=b.villagedm )a ORDER BY ccl desc,code  ";
            }
            if (param.code.Length == 12)
            {
                sql = $@" select ckfhwggptzlsl ,case when  ((COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)))>0 then ((COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0))) else 0 end  sy,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name , code,xzq,xzqdm,towndm,town,CASE WHEN ccl > 100 THEN 100.00||'%' when ckfhwggptzlsl=0 then 0.00||'%'  when ccl is null then 0.00||'%' ELSE ccl||'%' END  ccl from (				
		select  zcount, code,name,xzqdm,xzq,towndm,town,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,villagedm code,max(village) name,max(towndm) towndm,max(town) town,max(xzq) xzq,max(xzqdm) xzqdm,case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  (SELECT t4.region_name AS village,
    t1.villagedm,
    t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (((( SELECT count(1) AS zcount,
            mm.villagedm,
            mm.xzq,
            mm.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""其它"",
            mm.towndm
           FROM zm_buildings mm
          WHERE (NOT ((mm.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY mm.villagedm, mm.xzq, mm.xzqdm, mm.towndm
          ORDER BY mm.villagedm) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.village,
            zm_pc_base.town,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_by,
                    t1_1.create_on,
                    t1_1.create_ip,
                    t1_1.modified_by,
                    t1_1.modified_on,
                    t1_1.modified_ip,
                    t1_1.is_delete,
                    t1_1.delete_by,
                    t1_1.delete_on,
                    t1_1.delete_ip,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_pc_base.village, zm_pc_base.town, zm_pc_base.xzq, zm_pc_base.xzqdm) t2 ON (((t1.villagedm)::text = (t2.village)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
     LEFT JOIN zm_department t4 ON (((t1.villagedm)::text = (t4.id)::text)))
  ORDER BY t1.villagedm)jbxxcjview where villagedm like @code group by villagedm) a left join  (select villagedm,sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cjlog where villagedm like @code and create_on between  @startime and @endtime::TIMESTAMP group by villagedm)  b on a.code=b.villagedm )a ORDER BY ccl desc,code  ";
            }
            #endregion
            DateTime startime = DateTime.ParseExact(
          "2024-01-01",
          "yyyy-MM-dd",
          CultureInfo.InvariantCulture
      );
            var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @startime = startime, @endtime =endtime, @code = "%" + param.code + "%" }).ToList();
            //Dictionary<string, object> dictionary = new Dictionary<string, object>();
            //if (data != null)
            //{
            //    var properties = data as IDictionary<string, object>;
            //    foreach (var kvp in properties)
            //    {
            //        var stringlist = kvp.Value.ToString().Trim('[', ']').Split(", ");
            //        var list = new List<string>();
            //        foreach (var item in stringlist)
            //        {
            //            list.Add(item);
            //        }
            //        dictionary.Add(kvp.Key, list);
            //    }
            //    var r = new RespRet<object>(true, "Ok", dictionary);
            //    WriteSystemLog(usernNumber, "houses/hlccqk", r);
            //    return r;
            //}
            return new RespRet<object>(true, "Ok", data);
        }


        /// <summary>
        /// 护栏拆除情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/hlccqkmsg")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> hlccqkmsg([FromBody] DateQuery param)
        {
            //            string sql = @"    
            //  select sum(zcount) ckfhwggptzlsl,sum(ccfhwggptzlsl)ccfhwggptzlsl,round(COALESCE(sum(ccfhwggptzlsl)*1.00*100/sum(zcount),0.00),2)||'%'  ccl from (  select ckfhwggptzlsl zcount,(COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)) sy,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name , code,CASE WHEN ccl > 100 THEN 100.00  when ccl is null then 0.00 ELSE ccl END  ccl from (	select  zcount,code,name,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
            //case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select sum(zcount)zcount,xzqdm code,max(xzq) name, case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  jbxxgqview GROUP BY xzqdm) a left join (select xzqdm,sum(ccfhwggptzlsl) ccfhwggptzlsl From 	(select xzqdm,xzq,towndm,town,ckfhwggptzlsl zcount,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name , code  from (				
            //		select xzqdm,xzq,towndm,town,zcount, code,name,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
            //case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,max(xzqdm)xzqdm,max(xzq)xzq,max(towndm)towndm,max(town)town,villagedm code,max(village) name,case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  jbxxcjview  group by villagedm) a left join  (select villagedm,sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cjlog  group by villagedm)  b on a.code=b.villagedm )a ORDER BY ccl desc,code
            //) a   group by xzqdm)  b	 on a.code=b.xzqdm)a ORDER BY ccl desc,code) a  ";

            string formattedDate = DateTime.Today
 .AddHours(23)
 .AddMinutes(59)
 .AddSeconds(59)
 .ToString("yyyy-MM-dd HH:mm:ss");
            string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
            string sql = $@" select sum(zcount) ckfhwggptzlsl,sum(ccfhwggptzlsl)ccfhwggptzlsl,round(COALESCE(sum(ccfhwggptzlsl)*1.00*100/case when sum(zcount)=0 then 1 else sum(zcount) end,0.00),2)||'%'  ccl from (  select ckfhwggptzlsl zcount,(COALESCE(ckfhwggptzlsl,0) -COALESCE(ccfhwggptzlsl,0)) sy,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name , code,CASE WHEN ccl > 100 THEN 100.00  when ccl is null then 0.00 ELSE ccl END  ccl from (	select  zcount,code,name,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select sum(zcount)zcount,xzqdm code,max(xzq) name, case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  ( SELECT t1.xzq,
    t1.xzqdm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (( SELECT count(1) AS zcount,
            zm_buildings.xzq,
            zm_buildings.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""其它""
           FROM zm_buildings
          WHERE (NOT ((zm_buildings.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_buildings.xzqdm, zm_buildings.xzq) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_on,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime::text)))))
          GROUP BY zm_pc_base.xzqdm, zm_pc_base.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text)))
  ORDER BY t1.xzqdm)jbxxgqview GROUP BY xzqdm) a left join (select xzqdm,sum(ccfhwggptzlsl) ccfhwggptzlsl From 	(select xzqdm,xzq,towndm,town,ckfhwggptzlsl zcount,case when COALESCE(ccfhwggptzlsl,0)>COALESCE(ckfhwggptzlsl,0) then COALESCE(ckfhwggptzlsl,0) else COALESCE(ccfhwggptzlsl,0) end  ccfhwggptzlsl ,name , code  from (				
		select xzqdm,xzq,towndm,town,zcount, code,name,case when ckfhwggptzlsl is null then 0 else ckfhwggptzlsl end ckfhwggptzlsl,case when ccfhwggptzlsl is null then 0 else ccfhwggptzlsl end ccfhwggptzlsl  ,
case when 	round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) is null then 0.00 else round(ccfhwggptzlsl*1.0*100/ckfhwggptzlsl,2) end  ccl  from (select  sum(zcount)zcount,max(xzqdm)xzqdm,max(xzq)xzq,max(towndm)towndm,max(town)town,villagedm code,max(village) name,case when sum(ckfhwggptzlsl)=0 then null else  sum(ckfhwggptzlsl) end ckfhwggptzlsl from  ( SELECT t4.region_name AS village,
    t1.villagedm,
    t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (((( SELECT count(1) AS zcount,
            mm.villagedm,
            mm.xzq,
            mm.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""其它"",
            mm.towndm
           FROM zm_buildings mm
          WHERE (NOT ((mm.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text =@endtime::text)))))
          GROUP BY mm.villagedm, mm.xzq, mm.xzqdm, mm.towndm
          ORDER BY mm.villagedm) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.village,
            zm_pc_base.town,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_by,
                    t1_1.create_on,
                    t1_1.create_ip,
                    t1_1.modified_by,
                    t1_1.modified_on,
                    t1_1.modified_ip,
                    t1_1.is_delete,
                    t1_1.delete_by,
                    t1_1.delete_on,
                    t1_1.delete_ip,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = @endtime)))))
          GROUP BY zm_pc_base.village, zm_pc_base.town, zm_pc_base.xzq, zm_pc_base.xzqdm) t2 ON (((t1.villagedm)::text = (t2.village)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
     LEFT JOIN zm_department t4 ON (((t1.villagedm)::text = (t4.id)::text)))
  ORDER BY t1.villagedm)jbxxcjview  group by villagedm) a left join  (select villagedm,sum(ccfhwggptzlsl) ccfhwggptzlsl from zm_pc_gjzz_cjlog where  create_on between  @startime and @endtime::TIMESTAMP group by villagedm)  b on a.code=b.villagedm )a ORDER BY ccl desc,code
) a   group by xzqdm)  b	 on a.code=b.xzqdm)a ORDER BY ccl desc,code) a	 ";
            DateTime startime = DateTime.ParseExact(
          "2024-01-01",
          "yyyy-MM-dd",
          CultureInfo.InvariantCulture
      );
            var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @startime=startime, @endtime =formattedDate, @code = "%" + param.code + "%" }).ToList();
            return new RespRet<object>(true, "Ok", data);
        }



        /// <summary>
        /// 获取 北京市的总数量  自查数量  隐患数量  整改数量
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkratebj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngCheckBj([FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "user not logined");
            }
            string sql = @"select *,round((zccount*1.00/zcount)*100,2)|| '%' zcl  from (select sum(zcount) zcount,sum(zccount) zccount,sum(yhcount) yhcount,sum(zgcount) zgcount,'北京市' name,'110' code   from (select xzq name,xzqdm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount  from
               (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select count(fwbh) zcount,xzqdm,xzq  from zm_buildings group by  xzqdm,xzq ) t1 left join 
               (select coalesce(count(fwbh),0)  zccount,xzqdm from (select distinct(fwbh),xzqdm,id from zm_pc_base where yhly='1') tt group by  xzqdm) t2 on t1.xzqdm=t2.xzqdm  
                left join (select xzqdm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
                (select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
             left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by xzqdm) t3   on t1.xzqdm=t3.xzqdm
               )  tt order by yhcount desc ) hz) hx    limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql).ToList();
            int count = list.Count;

            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }


        /// <summary>
        /// 获取自查率 各区县的总数量  自查数量  隐患数量  整改数量
        /// </summary>
        /// <param name="pageRequest"></param>         
        /// <returns></returns>
        [HttpGet("houses/checkrategq")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngCheckQ([FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }

            //string sql = @"select xzq name,xzqdm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount  from
            //       (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select count(fwbh) zcount,xzqdm,xzq  from zm_buildings group by  xzqdm,xzq ) t1 left join 
            //       (select coalesce(count(fwbh),0)  zccount,xzqdm from (select distinct(fwbh),xzqdm,id from zm_pc_base where yhly='1') tt group by  xzqdm) t2 on t1.xzqdm=t2.xzqdm  
            //        left join (select xzqdm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
            //        (select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //     left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by xzqdm) t3   on t1.xzqdm=t3.xzqdm
            //       )  tt order by yhcount desc   limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            string sql = @" select *,replace(zcl, '%', '')::numeric value,xzq name,xzqdm code  from zcqkgqview  	";

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql).ToList();
            int count = list.Count;
            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }



        /// <summary>
        /// 获取自查率 各区县的总数量  自查数量  隐患数量  整改数量//带东西城
        /// </summary>
        /// <param name="pageRequest"></param>         
        /// <returns></returns>
        [HttpGet("houses/checkrategqdxc")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngCheckQDXC([FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }


            string time = DateTime.Today
 .AddHours(23)
 .AddMinutes(59)
 .AddSeconds(59)
 .ToString("yyyy-MM-dd HH:mm:ss");

            string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
            string sql = $@" select  * from ( select *,replace(zcl, '%', '')::numeric value,xzq name,xzqdm code  from ( SELECT tt.xzq,
    tt.xzqdm,
    tt.zcount,
    tt.zccount,
    concat(
        CASE
            WHEN (round((((tt.zccount)::numeric / (tt.zcount)::numeric) * (100)::numeric), 2) > (100)::numeric) THEN 100.00
            ELSE round((((tt.zccount)::numeric / (tt.zcount)::numeric) * (100)::numeric), 2)
        END, '%') AS zcl,
    COALESCE(
        CASE
            WHEN (((tt.zcount)::numeric - (tt.zccount)::numeric) < (0)::numeric) THEN (0)::numeric
            ELSE ((tt.zcount)::numeric - (tt.zccount)::numeric)
        END, (0)::numeric) AS wzccount,
    tt.yhcount,
    tt.zgcount,
    COALESCE((tt.yhcount - tt.zgcount), (0)::bigint) AS syyhcount
   FROM ( SELECT t1.xzq,
            t1.xzqdm,
            t1.zcount,
            COALESCE(t2.zccount, (0)::bigint) AS zccount,
            COALESCE(t3.yhcount, (0)::bigint) AS yhcount,
            COALESCE(t3.zgcount, (0)::bigint) AS zgcount
           FROM ((( SELECT zm_buildings.xzq,
                    zm_buildings.xzqdm,
                    count(1) AS zcount
                   FROM  zm_buildings
                  where fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
                  GROUP BY zm_buildings.xzqdm, zm_buildings.xzq) t1
             LEFT JOIN ( SELECT zm_pc_yh.xzqdm,
                    zm_pc_yh.xzq,
                    count(DISTINCT zm_pc_yh.fwbh) AS zccount
                   FROM  zm_pc_yh
                  WHERE fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
                  GROUP BY zm_pc_yh.xzqdm, zm_pc_yh.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text)))
             LEFT JOIN ( SELECT count(*) AS yhcount,
                    sum(
                        CASE
                            WHEN (zm_pc_yhlog_dx.zg_value = 1) THEN 1
                            ELSE 0
                        END) AS zgcount,
                    zm_pc_yhlog_dx.xzqdm,
                    zm_pc_yhlog_dx.xzq
                   FROM zm_pc_yhlog_dx
                  WHERE  fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
                  GROUP BY zm_pc_yhlog_dx.xzqdm, zm_pc_yhlog_dx.xzq) t3 ON (((t1.xzqdm)::text = (t3.xzqdm)::text)))) tt
  ORDER BY tt.xzqdm) zcqkgqview
union all
select '东城区','110101',0,0,0||'%',0,0,0,0,0,'东城区','110101'
union all
select '西城区','110102',0,0,0||'%',0,0,0,0,0,'西城区','110102')a ORDER BY xzqdm  	";

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql).ToList();
            int count = list.Count;
            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }

        /// <summary>
        /// 获取自查率 各乡镇的总数量  自查数量 自查整改数量  自查隐患数量等
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkrategxz")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngCheckxz([FromQuery] string code, [FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }


            //string sql = @"select town name,towndm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount  from (
            //        select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select count(fwbh) zcount,towndm,town  from zm_buildings group by  towndm,town ) t1 left join 
            //        (select coalesce(count(fwbh),0)  zccount,town towndm from (select distinct(fwbh),town from zm_pc_base where yhly='1') tt group by  towndm)t2 on t1.towndm=t2.towndm 
            //        left join (select towndm,sum(yhcount) yhcount,sum(zgcount)  zgcount from (
            //        select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //       left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by towndm) t3   on t1.towndm=t3.towndm
            //       )  tt   where  towndm like '" + code + "%'  order by yhcount desc     limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;

            string sql = @" select *,replace(zcl, '%', '')::numeric value,town name,towndm code  from zcqkxzview where towndm like @code	";

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql, new { @code = "%" + code + "%" }).ToList();
            int count = list.Count;

            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }


        /// <summary>
        /// 获取自查率 各村的总数量  自查数量 自查整改数量  自查隐患数量等
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkrategcj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngCheckcj([FromQuery] string code, [FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }


            if (code != null && code.EndsWith("000"))
            {
                code = code.Substring(0, 9);
            }


            //string sql = @"select village name,villagedm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount   from (
            //           select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount  from (select count(fwbh) zcount,villagedm,village from zm_buildings  group by  villagedm,village 
            //     ) t1 left join 
            //    (select coalesce(count(fwbh),0)  zccount,village villagedm from (select distinct(fwbh),village from zm_pc_base where yhly='1') tt group by  villagedm) t2 on t1.villagedm=t2.villagedm 
            //    left join (select villagedm,sum(yhcount) yhcount,sum(zgcount)  zgcount from (
            //      select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //     left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by villagedm) t3   on t1.villagedm=t3.villagedm
            //    )  tt   where  villagedm like '" + code + "%'  order by yhcount desc        limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            string sql = @" select *,replace(zcl, '%', '')::numeric value,village name,villagedm code  from zcqkcjview where villagedm like @code	";

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql, new { @code = "%" + code + "%" }).ToList();
            int count = list.Count;

            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }
        #endregion





        #region
        /// <summary>
        /// 获取检查率 各区县的总数量  检查数量  隐患数量  整改数量
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/Jcrategq")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngJcQ([FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }

            //string sql = @"select xzq name,xzqdm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount  from
            //       (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select count(fwbh) zcount,xzqdm,xzq  from zm_buildings group by  xzqdm,xzq ) t1 left join 
            //       (select coalesce(count(fwbh),0)  zccount,xzqdm from (select distinct(fwbh),xzqdm,id from zm_pc_base where yhly='1') tt group by  xzqdm) t2 on t1.xzqdm=t2.xzqdm  
            //        left join (select xzqdm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
            //        (select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //     left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by xzqdm) t3   on t1.xzqdm=t3.xzqdm
            //       )  tt order by yhcount desc   limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            string sql = @" select xzq name,xzqdm code,round((zccount*100*1.00/zcount),2) || '%' zcl,round((zccount*100*1.00/zcount),2) value,zcount,zccount,yhcount,zgcount  from
               (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select sum(fwds::int) zcount,xzqdm,xzq  from zm_building_ledger group by  xzqdm,xzq ) t1 left join 
               (select coalesce(count(fwbh),0)  zccount,xzqdm from (select distinct(fwbh),xzqdm,id from zm_pc_yh_cj ) tt group by  xzqdm) t2 on t1.xzqdm=t2.xzqdm  
                left join (select xzqdm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
                (select count(*) yhcount,fwbh,max(xzqdm) xzqdm ,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx_cj where fwbh in (select distinct(fwbh) from zm_pc_yh_cj ) and jcly='1' group by fwbh) t4
              group by xzqdm) t3   on t1.xzqdm=t3.xzqdm
               )  tt order by code 	   limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql).ToList();
            int count = list.Count;
            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }

        /// <summary>
        /// 获取检查率 各乡镇的总数量  自查数量 自查整改数量  自查隐患数量等
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/Jcrategxz")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngJcxz([FromQuery] string code, [FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }


            //string sql = @"select town name,towndm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount  from (
            //        select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select count(fwbh) zcount,towndm,town  from zm_buildings group by  towndm,town ) t1 left join 
            //        (select coalesce(count(fwbh),0)  zccount,town towndm from (select distinct(fwbh),town from zm_pc_base where yhly='1') tt group by  towndm)t2 on t1.towndm=t2.towndm 
            //        left join (select towndm,sum(yhcount) yhcount,sum(zgcount)  zgcount from (
            //        select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //       left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by towndm) t3   on t1.towndm=t3.towndm
            //       )  tt   where  towndm like '" + code + "%'  order by yhcount desc     limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;

            string sql = @"select town name,towndm code,round((zccount*100*1.00/zcount),2) || '%' zcl,round((zccount*100*1.00/zcount),2) value,zcount,zccount,yhcount,zgcount  from
               (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select sum(fwds::int) zcount,towndm,town  from zm_building_ledger group by  towndm,town ) t1 left join 
               (select coalesce(count(fwbh),0)  zccount,towndm from (select distinct(fwbh),towndm,id from zm_pc_yh_cj ) tt group by  towndm) t2 on t1.towndm=t2.towndm  
                left join (select towndm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
                (select count(*) yhcount,fwbh,max(towndm) towndm ,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx_cj where fwbh in (select distinct(fwbh) from zm_pc_yh_cj ) and jcly='1' group by fwbh) t4
              group by towndm) t3   on t1.towndm=t3.towndm
               )  tt where towndm like @code order by code 	";
            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql, new { @code = "%" + code + "%" }).ToList();
            int count = list.Count;

            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }


        /// <summary>
        /// 获取检查率 各村的总数量  自查数量 自查整改数量  自查隐患数量等
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/Jcrategcj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngJccj([FromQuery] string code, [FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }


            if (code != null && code.EndsWith("000"))
            {
                code = code.Substring(0, 9);
            }


            //string sql = @"select village name,villagedm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount   from (
            //           select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount  from (select count(fwbh) zcount,villagedm,village from zm_buildings  group by  villagedm,village 
            //     ) t1 left join 
            //    (select coalesce(count(fwbh),0)  zccount,village villagedm from (select distinct(fwbh),village from zm_pc_base where yhly='1') tt group by  villagedm) t2 on t1.villagedm=t2.villagedm 
            //    left join (select villagedm,sum(yhcount) yhcount,sum(zgcount)  zgcount from (
            //      select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //     left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by villagedm) t3   on t1.villagedm=t3.villagedm
            //    )  tt   where  villagedm like '" + code + "%'  order by yhcount desc        limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            string sql = @"select village name,villagedm code,round((zccount*100*1.00/zcount),2) || '%' zcl,round((zccount*100*1.00/zcount),2) value,zcount,zccount,yhcount,zgcount  from
               (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select sum(fwds::int) zcount,villagedm,village  from zm_building_ledger group by  villagedm,village ) t1 left join 
               (select coalesce(count(fwbh),0)  zccount,villagedm from (select distinct(fwbh),villagedm,id from zm_pc_yh_cj ) tt group by  villagedm) t2 on t1.villagedm=t2.villagedm  
                left join (select villagedm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
                (select count(*) yhcount,fwbh,max(villagedm) villagedm ,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx_cj where fwbh in (select distinct(fwbh) from zm_pc_yh_cj ) and jcly='1' group by fwbh) t4
              group by villagedm) t3   on t1.villagedm=t3.villagedm
               )  tt where villagedm like @code order by code	";

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql, new { @code = "%" + code + "%" }).ToList();
            int count = list.Count;

            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }

        #endregion


        #region
        /// <summary>
        /// 获取核查率 各区县的总数量  检查数量  隐患数量  整改数量
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/Hcrategq")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngHcQ([FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }

            //string sql = @"select xzq name,xzqdm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount  from
            //       (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select count(fwbh) zcount,xzqdm,xzq  from zm_buildings group by  xzqdm,xzq ) t1 left join 
            //       (select coalesce(count(fwbh),0)  zccount,xzqdm from (select distinct(fwbh),xzqdm,id from zm_pc_base where yhly='1') tt group by  xzqdm) t2 on t1.xzqdm=t2.xzqdm  
            //        left join (select xzqdm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
            //        (select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //     left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by xzqdm) t3   on t1.xzqdm=t3.xzqdm
            //       )  tt order by yhcount desc   limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            string sql = @" select xzq name,xzqdm code,round((zccount*100*1.00/zcount),2) || '%' zcl,round((zccount*100*1.00/zcount),2) value,zcount,zccount,yhcount,zgcount  from
               (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select sum(fwds::int) zcount,xzqdm,xzq  from zm_building_ledger group by  xzqdm,xzq ) t1 left join 
               (select coalesce(count(fwbh),0)  zccount,xzqdm from (select distinct(fwbh),xzqdm,id from zm_pc_yh_xz ) tt group by  xzqdm) t2 on t1.xzqdm=t2.xzqdm  
                left join (select xzqdm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
                (select count(*) yhcount,fwbh,max(xzqdm) xzqdm ,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx_xz where fwbh in (select distinct(fwbh) from zm_pc_yh_xz ) and jcly='1' group by fwbh) t4
              group by xzqdm) t3   on t1.xzqdm=t3.xzqdm
               )  tt order by code 	   limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql).ToList();
            int count = list.Count;
            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }

        /// <summary>
        /// 获取核查率 各乡镇的总数量  自查数量 自查整改数量  自查隐患数量等
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/Hcrategxz")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngHcxz([FromQuery] string code, [FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }


            //string sql = @"select town name,towndm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount  from (
            //        select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select count(fwbh) zcount,towndm,town  from zm_buildings group by  towndm,town ) t1 left join 
            //        (select coalesce(count(fwbh),0)  zccount,town towndm from (select distinct(fwbh),town from zm_pc_base where yhly='1') tt group by  towndm)t2 on t1.towndm=t2.towndm 
            //        left join (select towndm,sum(yhcount) yhcount,sum(zgcount)  zgcount from (
            //        select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //       left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by towndm) t3   on t1.towndm=t3.towndm
            //       )  tt   where  towndm like '" + code + "%'  order by yhcount desc     limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;

            string sql = @"select town name,towndm code,round((zccount*100*1.00/zcount),2) || '%' zcl,round((zccount*100*1.00/zcount),2) value,zcount,zccount,yhcount,zgcount  from
               (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select sum(fwds::int) zcount,towndm,town  from zm_building_ledger group by  towndm,town ) t1 left join 
               (select coalesce(count(fwbh),0)  zccount,towndm from (select distinct(fwbh),towndm,id from zm_pc_yh_xz ) tt group by  towndm) t2 on t1.towndm=t2.towndm  
                left join (select towndm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
                (select count(*) yhcount,fwbh,max(towndm) towndm ,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx_xz where fwbh in (select distinct(fwbh) from zm_pc_yh_xz ) and jcly='1' group by fwbh) t4
              group by towndm) t3   on t1.towndm=t3.towndm
               )  tt where towndm like @code order by code 	";

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql, new { @code = "%" + code + "%" }).ToList();
            int count = list.Count;

            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }


        /// <summary>
        /// 获取核查率 各村的总数量  自查数量 自查整改数量  自查隐患数量等
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/Hcrategcj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingPcRategj>>), 200)]
        public RespRet<Page<BuildingPcRategj>> HouseMngHccj([FromQuery] string code, [FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildingPcRategj>>(false, "PageIndex must >= 0");
            }


            if (code != null && code.EndsWith("000"))
            {
                code = code.Substring(0, 9);
            }


            //string sql = @"select village name,villagedm code,round((zccount/zcount)*100,2)|| '%' zcl,zcount,zccount,yhcount,zgcount   from (
            //           select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount  from (select count(fwbh) zcount,villagedm,village from zm_buildings  group by  villagedm,village 
            //     ) t1 left join 
            //    (select coalesce(count(fwbh),0)  zccount,village villagedm from (select distinct(fwbh),village from zm_pc_base where yhly='1') tt group by  villagedm) t2 on t1.villagedm=t2.villagedm 
            //    left join (select villagedm,sum(yhcount) yhcount,sum(zgcount)  zgcount from (
            //      select count(*) yhcount,fwbh,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx where fwbh in (select distinct(fwbh) from zm_pc_base where yhly='1') and jcly='1' group by fwbh) t4
            //     left join zm_buildings t5 on t4.fwbh=t5.fwbh  group by villagedm) t3   on t1.villagedm=t3.villagedm
            //    )  tt   where  villagedm like '" + code + "%'  order by yhcount desc        limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            string sql = @"select village name,villagedm code,round((zccount*100*1.00/zcount),2) || '%' zcl,round((zccount*100*1.00/zcount),2) value,zcount,zccount,yhcount,zgcount  from
               (select t1.*,coalesce(t2.zccount,0)  zccount,coalesce(t3.yhcount,0) yhcount,coalesce(t3.zgcount,0) zgcount from (select sum(fwds::int) zcount,villagedm,village  from zm_building_ledger group by  villagedm,village ) t1 left join 
               (select coalesce(count(fwbh),0)  zccount,villagedm from (select distinct(fwbh),villagedm,id from zm_pc_yh_xz ) tt group by  villagedm) t2 on t1.villagedm=t2.villagedm  
                left join (select villagedm,sum(yhcount) yhcount,sum(zgcount)  zgcount from 
                (select count(*) yhcount,fwbh,max(villagedm) villagedm ,sum(case when zg_value='1' then 1 else 0 end)  zgcount  from zm_pc_yhlog_dx_xz where fwbh in (select distinct(fwbh) from zm_pc_yh_xz ) and jcly='1' group by fwbh) t4
              group by villagedm) t3   on t1.villagedm=t3.villagedm
               )  tt where villagedm like @code order by code	";

            var list = _dbContext.Database.GetDbConnection().Query<BuildingPcRategj>(sql, new { @code = "%" + code + "%" }).ToList();
            int count = list.Count;

            var pageData = new Page<BuildingPcRategj>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildingPcRategj>>(true, "Ok", pageData);
        }
        #endregion

        static List<string> ConvertObjectFieldsToList(object obj)
        {
            List<string> stringList = new List<string>();
            // Use reflection to get type information
            Type type = obj.GetType();
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (PropertyInfo property in properties)
            {
                // Get the value of each property
                object value = property.GetValue(property, null); // Pass null for no parameters
                                                                  // Convert the value to string (or "null" if it's null)
                string stringValue = (value != null) ? value.ToString() : "null";
                // Add the string value to the list
                stringList.Add(stringValue);
            }

            return stringList;
        }

        #region 新大屏



        #region 中间列开始

        /// <summary>
        /// 今日自查@检查
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_21zcjc")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> dp_21zcjc([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                DateTime startimetodayMidnight = DateTime.Today;
                DateTime endtimeyesterday = DateTime.Today.AddDays(1).AddSeconds(-1);

                string sql = "";
                string RegionCode = param.code;
                string strtypetable = "";
                string strlname = "";

                param.endtime = DateTime.Today
.AddHours(23)
.AddMinutes(59)
.AddSeconds(59);
                param.startime = DateTime.Today.AddDays(-7);
                string time = DateTime.Today
.AddHours(23)
.AddMinutes(59)
.AddSeconds(59)
.ToString("yyyy-MM-dd HH:mm:ss");


                string yesterday = DateTime.Today.AddDays(-1)
.AddHours(23)
.AddMinutes(59)
.AddSeconds(59)
.ToString("yyyy-MM-dd HH:mm:ss");

                string yesterdaystart = DateTime.Today.AddDays(-1)
.ToString("yyyy-MM-dd HH:mm:ss");

                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;



                {
                    sql = @$"  	select * from 	
(select (round(zccount*1.00*100/zcount,2)) zcl from (select count(1) zcount,(select count(distinct fwbh) zccount from zm_pc_yhlog where create_on BETWEEN '{param.startime}' and '{param.endtime}' and fwbh not in (select fwbh From {table_name} where final_create_on='{endtimeyesterday}' and final_fwzt is not null)
) from zm_buildings where  fwbh not in (select fwbh From {table_name} where final_create_on='{param.endtime}'  and final_fwzt is not null)) tt)as t1,
(select (round(zccount*1.00*100/zcount,2)) jzhcl from (select count(1) zcount,(select count(distinct fwbh) zccount from zm_pc_yhlog_sqjz  where  jcly='4' and create_on  BETWEEN '{param.startime}' and  '{param.endtime}' and fwbh not in (select fwbh From {table_name} where final_create_on='{endtimeyesterday}' and final_fwzt is not null)
) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{param.endtime}'  and final_fwzt is not null))tt2) as t2,
(select zccount as  yesterdayzc from (select count(1) zcount,(select count(distinct fwbh) zccount from zm_pc_yhlog where create_on BETWEEN  '{yesterdaystart}' and '{yesterday}' and fwbh not in (select fwbh From {table_name} where final_create_on='{yesterday}' and final_fwzt is not null)
) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{param.endtime}'  and final_fwzt is not null))tt3) as t5,
(select zccount as  yesterdayjzhc from (select count(1) zcount,(select count(distinct fwbh) zccount from zm_pc_yhlog_sqjz where jcly='4' and create_on BETWEEN '{yesterdaystart}' and '{yesterday}' and fwbh not in (select fwbh From {table_name} where final_create_on='{yesterday}' and final_fwzt is not null)
) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{param.endtime}'  and final_fwzt is not null))tt4)as  t6,
(select zccount as  nowdayzc from (select count(1) zcount,(select count(distinct fwbh) zccount from zm_pc_yhlog where create_on BETWEEN '{startimetodayMidnight}' and '{endtimeyesterday}' and fwbh not in (select fwbh From {table_name} where final_create_on='{endtimeyesterday}' and final_fwzt is not null)
) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{param.endtime}'  and final_fwzt is not null))tt5) as t9,
(select zccount as  nowdayjzhc from (select count(1) zcount,(select count(distinct fwbh) zccount from zm_pc_yhlog_sqjz where jcly='4' and create_on BETWEEN '{startimetodayMidnight}' and '{endtimeyesterday}' and fwbh not in (select fwbh From {table_name} where final_create_on='{endtimeyesterday}' and final_fwzt is not null)
) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{param.endtime}'  and final_fwzt is not null))tt5) as t10 ";
//                    if (!string.IsNullOrEmpty(param.code))
//                    {
//                        sql = @$"select * from 	
//(select (round(zccount*1.00*100/zcount,2)) zcl from (select count(1) zcount,(select count(1) zccount from zm_pc_yhlog where date(create_on) BETWEEN '{param.startime}' and ' { param.endtime}'  and xzqdm='{param.code}' and fwbh not  in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
//) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)) tt)as t1,
//(select (round(zccount*1.00*100/zcount,2)) jcl from (select count(1) zcount,(select count(1) zccount from zm_pc_yhlog_cj where date(create_on) BETWEEN '{param.startime}' and '{param.endtime}'  and xzqdm='{ param.code}' and fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
//) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null))tt2) as t2,
//(select zccount as  yesterdayzc from (select count(1) zcount,(select count(1) zccount from zm_pc_yhlog where date(create_on) BETWEEN '{startimetodayMidnight.AddDays(-1)}' and '{endtimeyesterday.AddDays(-1)}'  and xzqdm='{param.code}' and fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
//) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null))tt3) as t3,
//(select zccount as  yesterdayjc from (select count(1) zcount,(select count(1) zccount from zm_pc_yhlog_cj where date(create_on) BETWEEN '{startimetodayMidnight.AddDays(-1)}' and '{endtimeyesterday.AddDays(-1)}'  and xzqdm='{param.code}' and fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
//) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null))tt4)as  t4,
//(select zccount as  nowdayzc from (select count(1) zcount,(select count(1) zccount from zm_pc_yhlog where date(create_on) BETWEEN '{ startimetodayMidnight}' and '{ endtimeyesterday}' and xzqdm='{param.code}' and fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
//) from zm_buildings where fwbh not in (select fwbh From  {table_name} where final_create_on='{time}' and final_fwzt is not null))tt5) as t5,
//(select zccount as  nowdayjc from (select count(1) zcount,(select count(1) zccount from zm_pc_yhlog_cj where date(create_on) BETWEEN '{ startimetodayMidnight}' and '{endtimeyesterday}' and xzqdm='{param.code}' and fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null)
//) from zm_buildings where fwbh not in (select fwbh From {table_name} where final_create_on='{time}' and final_fwzt is not null))tt6)as  t6
//";
//                    }
                }
                //优化转
                var data = _dbContext.Database.GetDbConnection().Query<dynamic>(sql, null).FirstOrDefault();
                if (data != null)
                {
                    var dictionary = ((IDictionary<string, object>)data).ToDictionary(kvp => kvp.Key, kvp =>
                    {
                        var stringList = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        return stringList.ToList();
                    });
                    var response = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/dp_21zcjc", response);
                    return response;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/dp_21zcjc", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/dp_21zcjc", res);
                res.Msg = "系统异常" + ex.Message;
                return res;
            }
        }



        /// <summary>
        /// 基础信息，不区分时间、默认自查
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/dp_23jcxx")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(BuildingJbxx), 200)]
        public RespRet<List<Modelbuilding>> dp_23jcxx([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string time = DateTime.Today
    .AddHours(23)
    .AddMinutes(59)
    .AddSeconds(59)
    .ToString("yyyy-MM-dd HH:mm:ss");

                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                string sql = $@" 																
			SELECT 
    CASE WHEN SUM(zzrs) IS NULL THEN 0 ELSE SUM(zzrs) END AS zzrksl,
    CASE WHEN SUM(jzrks) IS NULL THEN 0 ELSE SUM(jzrks) END AS jzrks,
    CASE WHEN SUM(jzfjs) IS NULL THEN 0 ELSE SUM(jzfjs) END AS czfjsl,
    CASE WHEN SUM(csjyssl) IS NULL THEN 0 ELSE SUM(csjyssl) END AS csjyssl,
    CASE WHEN SUM(xggdjsbp) IS NULL THEN 0 ELSE SUM(xggdjsbp) END AS xggdjsbp,
    CASE WHEN SUM(bdfwjzrydddzxcsl) IS NULL THEN 0 ELSE SUM(bdfwjzrydddzxcsl) END AS ddzxcsl,
    CASE WHEN SUM(czryrs) IS NULL THEN 0 ELSE SUM(czryrs) END AS czryrsl,
    CASE WHEN SUM(cjzwqtjyyt) IS NULL THEN 0 ELSE SUM(cjzwqtjyyt) END AS cjzwqtjyyt
FROM 
   ( SELECT t1.xzq,
    t1.xzqdm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (( SELECT count(1) AS zcount,
            zm_buildings.xzq,
            zm_buildings.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""其它""
           FROM zm_buildings
          WHERE (NOT ((zm_buildings.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY zm_buildings.xzqdm, zm_buildings.xzq) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_on,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text ='{time}'::text)))))
          GROUP BY zm_pc_base.xzqdm, zm_pc_base.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text)))
  ORDER BY t1.xzqdm) jbxxgqview; ";
                if (!string.IsNullOrEmpty(pageRequest.xzqdm))
                {
                    sql = $@"             	
		            									SELECT 
    xzq,xzqdm,
    CASE WHEN (zzrs) IS NULL THEN 0 ELSE (zzrs) END AS zzrksl,
    CASE WHEN (jzrks) IS NULL THEN 0 ELSE (jzrks) END AS jzrks,
    CASE WHEN (jzfjs) IS NULL THEN 0 ELSE (jzfjs) END AS czfjsl,
    CASE WHEN (csjyssl) IS NULL THEN 0 ELSE (csjyssl) END AS csjyssl,
    CASE WHEN (xggdjsbp) IS NULL THEN 0 ELSE (xggdjsbp) END AS xggdjsbp,
    CASE WHEN (bdfwjzrydddzxcsl) IS NULL THEN 0 ELSE (bdfwjzrydddzxcsl) END AS ddzxcsl,
    CASE WHEN (czryrs) IS NULL THEN 0 ELSE (czryrs) END AS czryrsl,
    CASE WHEN (cjzwqtjyyt) IS NULL THEN 0 ELSE (cjzwqtjyyt) END AS cjzwqtjyyt
FROM ( SELECT t1.xzq,
    t1.xzqdm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (( SELECT count(1) AS zcount,
            zm_buildings.xzq,
            zm_buildings.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""其它""
           FROM zm_buildings
          WHERE (NOT ((zm_buildings.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY zm_buildings.xzqdm, zm_buildings.xzq) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_on,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY zm_pc_base.xzqdm, zm_pc_base.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text)))
  ORDER BY t1.xzqdm) jbxxgqview
                    where xzqdm='" + pageRequest.xzqdm + "'";
                }
                var res = _dbContext.Database.GetDbConnection().Query<BuildingJbxx>(sql).FirstOrDefault();  //一行
                List<Modelbuilding> models = new List<Modelbuilding>();
                Modelbuilding model = new Modelbuilding();
                model = new Modelbuilding();
                model.name = "行政区";
                model.value = res.xzq;
                model.unit = "";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "行政区代码";
                model.value = res.xzqdm;
                model.unit = "";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "租住人口数量";
                model.value = res.zzrksl;
                model.unit = "人";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "出租房间数量";
                model.value = res.czfjsl;
                model.unit = "间";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "电动自行车数量";
                model.value = res.ddzxcsl;
                model.unit = "辆";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "其他经营业态";
                model.value = res.cjzwqtjyyt;
                model.unit = "个";
                models.Add(model);
                return new RespRet<List<Modelbuilding>>(true, "Ok", models);
            }
            catch (Exception ex)
            {
                return null;
            }
        }



        /// <summary>
        /// 基础信息【2级】
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_23jcxx2j")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> dp_23jcxx2j([FromBody] DateQuery param)
        {
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }
                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                string sql = "";
                string RegionCode = param.code;


                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                string time = DateTime.Today
    .AddHours(23)
    .AddMinutes(59)
    .AddSeconds(59)
    .ToString("yyyy-MM-dd HH:mm:ss");

                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                string strtype = "z";
                string strtypezd = "zc";
                if (param.type == "1")
                {
                    strtype = "z";
                    strtypezd = "zcl";
                }
                else
                {
                    strtype = "j";
                    strtypezd = "jcl";
                }
                if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                {
                    #region
                    sql = $@"             	
		   SELECT 
				xzq,xzqdm,zzrs,jzrks,jzfjs,csjyssl,xggdjsbp,bdfwjzrydddzxcsl,czryrs,cjzwqtjyyt,""餐饮"",""商店"",""美容美发"",""KTV"",""网吧"",""美甲美睫"",""棋牌室"",""茶社"",""足疗、按摩"",""教学培训"",""医疗诊所"",""加工生产"",""其它""

        FROM 
           ( SELECT t1.xzq,
    t1.xzqdm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (( SELECT count(1) AS zcount,
            zm_buildings.xzq,
            zm_buildings.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (zm_buildings.xzqdm)::text)) AS ""其它""
           FROM zm_buildings
          WHERE (NOT ((zm_buildings.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY zm_buildings.xzqdm, zm_buildings.xzq) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_on,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY zm_pc_base.xzqdm, zm_pc_base.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text)))
  ORDER BY t1.xzqdm) jbxxgqview 
   ";
                    #endregion
                }
                else if (RegionCode.Length == 6)
                {
                    #region
                    sql = $@"  	  	  	
	SELECT
	town,
	towndm,
	xzq,
	xzqdm,
	zzrs,
jzrks,
	jzfjs,
	csjyssl,
	xggdjsbp,
	bdfwjzrydddzxcsl,
	czryrs,
	cjzwqtjyyt,""餐饮"",""商店"",""美容美发"",""KTV"",""网吧"",""美甲美睫"",""棋牌室"",""茶社"",""足疗、按摩"",""教学培训"",""医疗诊所"",""加工生产"",""其它""

FROM
	( SELECT t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM ((( SELECT count(1) AS zcount,
            zm_buildings.towndm,
            zm_buildings.xzq,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (zm_buildings.towndm)::text)) AS ""其它"",
            zm_buildings.xzqdm
           FROM zm_buildings
          WHERE (NOT ((zm_buildings.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY zm_buildings.towndm, zm_buildings.xzq, zm_buildings.xzqdm
          ORDER BY zm_buildings.towndm) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.town
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_by,
                    t1_1.create_on,
                    t1_1.create_ip,
                    t1_1.modified_by,
                    t1_1.modified_on,
                    t1_1.modified_ip,
                    t1_1.is_delete,
                    t1_1.delete_by,
                    t1_1.delete_on,
                    t1_1.delete_ip,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs,
                    t2_1.fwzt
                   FROM (zm_pc_base t1_1
                     LEFT JOIN zm_pc_base_cj t2_1 ON (((t1_1.fwbh)::text = (t2_1.fwbh)::text)))) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY zm_pc_base.town) t2 ON (((t1.towndm)::text = (t2.town)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
  ORDER BY t1.towndm)jbxxxzview
where xzqdm='" + RegionCode + "'";
                    #endregion
                }
                else if (RegionCode.Length == 12)
                {
                    #region
                    sql = $@" 
    SELECT
	town,
	towndm,
	xzq,
	xzqdm,
	village,
	villagedm,
	zzrs,
jzrks,
	jzfjs,
	csjyssl,
	xggdjsbp,
	bdfwjzrydddzxcsl,
	czryrs,
	cjzwqtjyyt,""餐饮"",""商店"",""美容美发"",""KTV"",""网吧"",""美甲美睫"",""棋牌室"",""茶社"",""足疗、按摩"",""教学培训"",""医疗诊所"",""加工生产"",""其它""

FROM
	( SELECT t4.region_name AS village,
    t1.villagedm,
    t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE(t2.jzrks, (0)::bigint) AS jzrks,
    COALESCE(t2.czryrs, (0)::bigint) AS czryrs,
    COALESCE(t2.cjzwqtjyyt, (0)::bigint) AS cjzwqtjyyt,
    COALESCE(t2.zzrs, (0)::bigint) AS zzrs,
    COALESCE(t2.fjsl, (0)::bigint) AS fjsl,
    COALESCE(t2.jzfjs, (0)::bigint) AS jzfjs,
    COALESCE(t2.jzscxyaqcksl, (0)::bigint) AS jzscxyaqcksl,
    COALESCE(t2.jzxyssltsl, (0)::bigint) AS jzxyssltsl,
    COALESCE(t2.ckfhwggptzlsl, (0)::bigint) AS ckfhwggptzlsl,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl,
    COALESCE(t2.mhqsl, (0)::bigint) AS mhqsl,
    COALESCE(t2.fytsmz, (0)::bigint) AS fytsmz,
    COALESCE(t2.xggdjsbp, (0)::bigint) AS xggdjsbp,
    COALESCE(t2.jzsyjyplmhxts, (0)::bigint) AS jzsyjyplmhxts,
    COALESCE(t2.jzszlwxdlgybjqs, (0)::bigint) AS jzszlwxdlgybjqs,
    COALESCE(t2.wdwhjgfjgqsyyrkrgbdj, (0)::bigint) AS wdwhjgfjgqsyyrkrgbdj,
    COALESCE(t2.sstdsyyrkrclzx, (0)::bigint) AS sstdsyyrkrclzx,
    COALESCE(t2.gryssdcsszblyyqksddp, (0)::bigint) AS gryssdcsszblyyqksddp,
    COALESCE(t2.csjyssl, (0)::bigint) AS csjyssl,
    COALESCE(t2.lcjzsl, (0)::bigint) AS lcjzsl,
    COALESCE(t2.ssltdbfjsl, (0)::bigint) AS ssltdbfjsl,
    COALESCE(t2.sstdywc, (0)::bigint) AS sstdywc,
    COALESCE(t2.zzsggz, (0)::bigint) AS zzsggz,
    COALESCE(t2.zzzdfa, (0)::bigint) AS zzzdfa,
    COALESCE(t2.jzswhntjzssslt, (0)::bigint) AS jzswhntjzssslt,
    COALESCE(t2.jzsnzssslt, (0)::bigint) AS jzsnzssslt,
    COALESCE((t1.""餐饮"")::numeric, (0)::numeric) AS ""餐饮"",
    COALESCE((t1.""商店"")::numeric, (0)::numeric) AS ""商店"",
    COALESCE((t1.""美容美发"")::numeric, (0)::numeric) AS ""美容美发"",
    COALESCE((t1.""KTV"")::numeric, (0)::numeric) AS ""KTV"",
    COALESCE((t1.""网吧"")::numeric, (0)::numeric) AS ""网吧"",
    COALESCE((t1.""美甲美睫"")::numeric, (0)::numeric) AS ""美甲美睫"",
    COALESCE((t1.""棋牌室"")::numeric, (0)::numeric) AS ""棋牌室"",
    COALESCE((t1.""茶社"")::numeric, (0)::numeric) AS ""茶社"",
    COALESCE((t1.""足疗、按摩"")::numeric, (0)::numeric) AS ""足疗、按摩"",
    COALESCE((t1.""教学培训"")::numeric, (0)::numeric) AS ""教学培训"",
    COALESCE((t1.""医疗诊所"")::numeric, (0)::numeric) AS ""医疗诊所"",
    COALESCE((t1.""加工生产"")::numeric, (0)::numeric) AS ""加工生产"",
    COALESCE((t1.""其它"")::numeric, (0)::numeric) AS ""其它"",
    COALESCE(t2.lyxlhxjjzss, (0)::bigint) AS lyxlhxjjzss
   FROM (((( SELECT count(1) AS zcount,
            mm.villagedm,
            mm.xzq,
            mm.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%餐饮%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""餐饮"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%商店%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""商店"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美容美发%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美容美发"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%KTV%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""KTV"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%网吧%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""网吧"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%美甲美睫%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""美甲美睫"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%棋牌室%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""棋牌室"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%茶社%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""茶社"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%足疗、按摩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""足疗、按摩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%教学培训%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""教学培训"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%医疗诊所%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""医疗诊所"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%加工生产%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""加工生产"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cjzwqtjyytmsg)::text ~~ '%其它%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (mm.villagedm)::text)) AS ""其它"",
            mm.towndm
           FROM zm_buildings mm
          WHERE (NOT ((mm.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY mm.villagedm, mm.xzq, mm.xzqdm, mm.towndm
          ORDER BY mm.villagedm) t1
     LEFT JOIN ( SELECT sum(zm_pc_base.jzrks) AS jzrks,
            sum(zm_pc_base.zzrs) AS zzrs,
            sum(zm_pc_base.czryrs) AS czryrs,
            sum(zm_pc_base.cjzwqtjyyt) AS cjzwqtjyyt,
            sum(zm_pc_base.fjsl) AS fjsl,
            sum(zm_pc_base.jzfjs) AS jzfjs,
            sum(zm_pc_base.jzscxyaqcksl) AS jzscxyaqcksl,
            sum(zm_pc_base.jzxyssltsl) AS jzxyssltsl,
            sum(zm_pc_base.ckfhwggptzlsl) AS ckfhwggptzlsl,
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            sum(zm_pc_base.mhqsl) AS mhqsl,
            sum(zm_pc_base.fytsmz) AS fytsmz,
            sum(zm_pc_base.xggdjsbp) AS xggdjsbp,
            sum(zm_pc_base.jzsyjyplmhxts) AS jzsyjyplmhxts,
            sum(zm_pc_base.jzszlwxdlgybjqs) AS jzszlwxdlgybjqs,
            sum(zm_pc_base.wdwhjgfjgqsyyrkrgbdj) AS wdwhjgfjgqsyyrkrgbdj,
            sum(zm_pc_base.sstdsyyrkrclzx) AS sstdsyyrkrclzx,
            sum(zm_pc_base.gryssdcsszblyyqksddp) AS gryssdcsszblyyqksddp,
            sum(
                CASE
                    WHEN (zm_pc_base.cs >= 3) THEN 1
                    ELSE 0
                END) AS csjyssl,
            sum(
                CASE
                    WHEN (zm_pc_base.cs = 2) THEN 1
                    ELSE 0
                END) AS lcjzsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.cs = 1) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    WHEN ((zm_pc_base.cs >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2) AND (zm_pc_base.jzscxyaqcksl >= 2)) THEN 1
                    ELSE 0
                END) AS ssltdbfjsl,
            sum(
                CASE
                    WHEN ((zm_pc_base.jsrysstd)::text = '已完成'::text) THEN 1
                    ELSE 0
                END) AS sstdywc,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在施工改造'::text) THEN 1
                    ELSE 0
                END) AS zzsggz,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text = '正在制定方案'::text) THEN 1
                    ELSE 0
                END) AS zzzdfa,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室外或内天井增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzswhntjzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%建筑室内增设疏散楼梯%'::text) THEN 1
                    ELSE 0
                END) AS jzsnzssslt,
            sum(
                CASE
                    WHEN ((zm_pc_base.sstdjsqk)::text ~~ '%利用相邻或相近建筑疏散%'::text) THEN 1
                    ELSE 0
                END) AS lyxlhxjjzss,
            zm_pc_base.village,
            zm_pc_base.town,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM ( SELECT t1_1.id,
                    t1_1.fwbh,
                    t1_1.yhly,
                    t1_1.xzqdm,
                    t1_1.town,
                    t1_1.village,
                    t1_1.address,
                    t1_1.yhfwbh,
                    t1_1.hzxm,
                    t1_1.jzrks,
                    t1_1.zzrs,
                    t1_1.cs,
                    t1_1.fjsl,
                    t1_1.jzfjs,
                    t1_1.jzscxyaqcksl,
                    t1_1.jzxyssltsl,
                    t1_1.jzscmj,
                    t1_1.ckfhwggptzlsl,
                    t1_1.bdfwjzrydddzxcsl,
                    t1_1.mhqsl,
                    t1_1.fytsmz,
                    t1_1.xggdjsbp,
                    t1_1.jzsyjyplmhxts,
                    t1_1.jzszlwxdlgybjqs,
                    t1_1.wdwhjgfjgqsyyrkrgbdj,
                    t1_1.sstdsyyrkrclzx,
                    t1_1.gryssdcsszblyyqksddp,
                    t1_1.cjzwqtjyytmsg,
                    t1_1.jsrysstd,
                    t1_1.sstdjsqk,
                    t1_1.create_by,
                    t1_1.create_on,
                    t1_1.create_ip,
                    t1_1.modified_by,
                    t1_1.modified_on,
                    t1_1.modified_ip,
                    t1_1.is_delete,
                    t1_1.delete_by,
                    t1_1.delete_on,
                    t1_1.delete_ip,
                    t1_1.pcsj,
                    t1_1.cjzwqtjyyt,
                    t1_1.xzq,
                    t1_1.towndm,
                    t1_1.villagedm,
                    t1_1.cdfs,
                    t1_1.cdfsqtbz,
                    t1_1.czryrs
                   FROM zm_pc_base t1_1) zm_pc_base
          WHERE (NOT ((zm_pc_base.fwbh)::text IN ( SELECT {table_name}.fwbh
                   FROM {table_name}
                  WHERE (({table_name}.final_fwzt IS NOT NULL) AND (({table_name}.final_create_on)::text = '{time}'::text)))))
          GROUP BY zm_pc_base.village, zm_pc_base.town, zm_pc_base.xzq, zm_pc_base.xzqdm) t2 ON (((t1.villagedm)::text = (t2.village)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
     LEFT JOIN zm_department t4 ON (((t1.villagedm)::text = (t4.id)::text)))
  ORDER BY t1.villagedm)jbxxcjview
where towndm='" + RegionCode + "'";
                    #endregion
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, null).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }

        /// <summary>
        /// 基础建设情况，攻坚整治
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/dp_24jcjsqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(Buildingjcjsqk), 200)]
        public RespRet<List<Modelbuilding>> dp_24jcjsqk([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string time = DateTime.Today
     .AddHours(23)
     .AddMinutes(59)
     .AddSeconds(59)
     .ToString("yyyy-MM-dd HH:mm:ss");

                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                string sql = @" 																
	SELECT COALESCE
	( SUM ( qcxycdjk ), 0 ) AS qcxycdjk,
	COALESCE ( SUM ( xfctdsl ), 0 ) AS xfctdsl,
	COALESCE ( SUM ( abzjsxfscsl ), 0 )+	COALESCE ( SUM ( pzxfsb ), 0 )  AS abzjsxfscsl,
	COALESCE ( SUM ( pzxfsb ), 0 ) AS pzxfsb,
	COALESCE ( SUM ( sfjszzxfdhxxxfz ), 0 ) AS sfjszzxfdhxxxfz,
	'北京市' AS xzq 
FROM
	zm_pc_gjzz_cj
																 ";

                if (!string.IsNullOrEmpty(pageRequest.code) && string.IsNullOrEmpty(pageRequest.xzqdm))
                {
                    pageRequest.xzqdm = pageRequest.code;
                }

                if (!string.IsNullOrEmpty(pageRequest.xzqdm))
                {
                    sql = $@"             	
	SELECT
	xzq,xzqdm,
	 COALESCE(  ( qcxycdjk ), 0 ) AS qcxycdjk,
	COALESCE (  ( xfctdsl ), 0 ) AS xfctdsl,
	COALESCE (  ( abzjsxfscsl ), 0 )+	COALESCE (  ( pzxfsb ), 0 )  AS abzjsxfscsl,
	COALESCE (  ( pzxfsb ), 0 ) AS pzxfsb,
	COALESCE (  ( sfjszzxfdhxxxfz ), 0 ) AS sfjszzxfdhxxxfz

FROM
	(SELECT
	t1.xzq,
	t1.xzqdm,
	COALESCE ( ( t1.zcount ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS zcount,
	COALESCE ( ( t2.qcxycdjk ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS qcxycdjk,
	COALESCE ( ( t2.xfctdsl ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS xfctdsl,
	COALESCE ( ( t2.abzjsxfscsl ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS abzjsxfscsl,
	COALESCE ( ( t2.pzxfsb ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS pzxfsb,
	COALESCE ( ( t2.sfjszzxfdhxxxfz ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS sfjszzxfdhxxxfz,
	COALESCE ( ( t1.""单插口"" ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS ""单插口"",
	COALESCE ( ( t1.""集中充电桩"" ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS ""集中充电桩"",
	COALESCE ( ( t1.""充(换)电柜"" ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS ""充(换)电柜"",
	COALESCE ( ( t1.""单仓"" ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS ""单仓"",
	COALESCE ( ( t1.""其他"" ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS ""其他"",
	COALESCE ( ( t2.twotoone ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS twotoone,
	COALESCE ( ( t2.onetoone ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS onetoone,
	COALESCE ( ( t2.tzzfybjcdssjk ) :: NUMERIC, ( 0 ) :: NUMERIC ) AS tzzfybjcdssjk,
	COALESCE ( t2.wwcbjssyjbjwcsj, ( 0 ) :: NUMERIC ) AS wwcbjssyjbjwcsj 
FROM
	(
		(
		SELECT COUNT
			( 1 ) AS zcount,
			t1_1.xzq,
			t1_1.xzqdm,
			(
			SELECT SUM
				( CASE WHEN ( ( zm_pc_base.cdfs ) :: TEXT ~~ '%单插口%' :: TEXT ) THEN 1 ELSE 0 END ) AS SUM 
			FROM
				zm_pc_base 
			WHERE
				( ( zm_pc_base.xzqdm ) :: TEXT = ( t1_1.xzqdm ) :: TEXT ) 
			) AS ""单插口"",
			(
			SELECT SUM
				( CASE WHEN ( ( zm_pc_base.cdfs ) :: TEXT ~~ '%集中充电桩%' :: TEXT ) THEN 1 ELSE 0 END ) AS SUM 
			FROM
				zm_pc_base 
			WHERE
				( ( zm_pc_base.xzqdm ) :: TEXT = ( t1_1.xzqdm ) :: TEXT ) 
			) AS ""集中充电桩"",
			(
			SELECT SUM
				( CASE WHEN ( ( zm_pc_base.cdfs ) :: TEXT ~~ '%充(换)电柜%' :: TEXT ) THEN 1 ELSE 0 END ) AS SUM 
			FROM
				zm_pc_base 
			WHERE
				( ( zm_pc_base.xzqdm ) :: TEXT = ( t1_1.xzqdm ) :: TEXT ) 
			) AS ""充(换)电柜"",
			(
			SELECT SUM
				( CASE WHEN ( ( zm_pc_base.cdfs ) :: TEXT ~~ '%单仓%' :: TEXT ) THEN 1 ELSE 0 END ) AS SUM 
			FROM
				zm_pc_base 
			WHERE
				( ( zm_pc_base.xzqdm ) :: TEXT = ( t1_1.xzqdm ) :: TEXT ) 
			) AS ""单仓"",
			(
			SELECT SUM
				( CASE WHEN ( ( zm_pc_base.cdfs ) :: TEXT ~~ '%其他%' :: TEXT ) THEN 1 ELSE 0 END ) AS SUM 
			FROM
				zm_pc_base 
			WHERE
				( ( zm_pc_base.xzqdm ) :: TEXT = ( t1_1.xzqdm ) :: TEXT ) 
			) AS ""其他"" 
		FROM
			zm_buildings t1_1 
		WHERE  fwbh not in  (select fwbh From  {table_name} where final_create_on='{time}'  and final_fwzt is not null  )
			fwbh NOT IN 
		GROUP BY
			t1_1.xzqdm,
			t1_1.xzq 
		ORDER BY
			t1_1.xzqdm 
		) t1
		LEFT JOIN (
		SELECT SUM
			( zm_pc_gjzz_cj.qcxycdjk ) AS qcxycdjk,
			SUM ( zm_pc_gjzz_cj.xfctdsl ) AS xfctdsl,
			SUM ( zm_pc_gjzz_cj.abzjsxfscsl ) AS abzjsxfscsl,
			SUM ( zm_pc_gjzz_cj.pzxfsb ) AS pzxfsb,
			SUM ( zm_pc_gjzz_cj.sfjszzxfdhxxxfz ) AS sfjszzxfdhxxxfz,
			SUM ( zm_pc_gjzz_cj.twotoone ) AS twotoone,
			SUM ( zm_pc_gjzz_cj.onetoone ) AS onetoone,
			SUM ( zm_pc_gjzz_cj.tzzfybjcdssjk ) AS tzzfybjcdssjk,
			SUM ( ( zm_pc_gjzz_cj.wwcbjssyjbjwcsj ) :: NUMERIC ) AS wwcbjssyjbjwcsj,
			zm_pc_gjzz_cj.xzq,
			zm_pc_gjzz_cj.xzqdm 
		FROM
			zm_pc_gjzz_cj 
		GROUP BY
			zm_pc_gjzz_cj.xzqdm,
			zm_pc_gjzz_cj.xzq 
		) t2 ON ( ( ( t1.xzqdm ) :: TEXT = ( t2.xzqdm ) :: TEXT ) ) 
	) 
ORDER BY
	t1.xzqdm)gjzz1gqview
                    where xzqdm='" + pageRequest.xzqdm + "'";
                }

                var res = _dbContext.Database.GetDbConnection().Query<Buildingjcjsqk>(sql).FirstOrDefault();  //一行
                List<Modelbuilding> models = new List<Modelbuilding>();
                Modelbuilding model = new Modelbuilding();

                model = new Modelbuilding();
                model.name = "行政区";
                model.value = res.xzq;
                model.unit = "";
                models.Add(model);
                model = new Modelbuilding();
                //model.name = "现有充电接口";
                model.name = "充电设施建设情况";
                model.value = res.qcxycdjk;
                model.unit = "个";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "建设消防通道";
                //model.name = "消防车通道数量";
                model.value = res.xfctdsl;
                model.unit = "条";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "建设水源数量";
                //model.name = "消防水池数量";
                model.value = res.abzjsxfscsl;
                model.unit = "个";
                models.Add(model);

                model = new Modelbuilding();
                //model.name = "专职消防队或小型消防站";
                model.name = "自防自救力量建设情况";
                model.value = res.sfjszzxfdhxxxfz;
                model.unit = "个";
                models.Add(model);
                return new RespRet<List<Modelbuilding>>(true, "Ok", models);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 基础建设情况【2级】
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_24jcjsqk2j")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> dp_24jcjsqk2j([FromBody] DateQuery param)
        {
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                string sql = "";
                string RegionCode = param.code;

                string strtype = "z";
                string strtypezd = "zc";
                if (param.type == "1")
                {
                    strtype = "z";
                    strtypezd = "zcl";
                }
                else
                {
                    strtype = "j";
                    strtypezd = "jcl";
                }
                string time = DateTime.Today
   .AddHours(23)
   .AddMinutes(59)
   .AddSeconds(59)
   .ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                {
                    #region
                    sql = $@"             	
				   SELECT 
				xzq,xzqdm,qcxycdjk,xfctdsl,abzjsxfscsl+pzxfsb as abzjsxfscsl,pzxfsb,sfjszzxfdhxxxfz,twotoone,onetoone,tzzfybjcdssjk,wwcbjssyjbjwcsj,""单插口"",""集中充电桩"",""充(换)电柜"",""单仓"",""其他""
        FROM 
           ( SELECT t1.xzq,
    t1.xzqdm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE((t2.qcxycdjk)::numeric, (0)::numeric) AS qcxycdjk,
    COALESCE((t2.xfctdsl)::numeric, (0)::numeric) AS xfctdsl,
    COALESCE((t2.abzjsxfscsl)::numeric, (0)::numeric) AS abzjsxfscsl,
    COALESCE((t2.pzxfsb)::numeric, (0)::numeric) AS pzxfsb,
    COALESCE((t2.sfjszzxfdhxxxfz)::numeric, (0)::numeric) AS sfjszzxfdhxxxfz,
    COALESCE((t1.""单插口"")::numeric, (0)::numeric) AS ""单插口"",
    COALESCE((t1.""集中充电桩"")::numeric, (0)::numeric) AS ""集中充电桩"",
    COALESCE((t1.""充(换)电柜"")::numeric, (0)::numeric) AS ""充(换)电柜"",
    COALESCE((t1.""单仓"")::numeric, (0)::numeric) AS ""单仓"",
    COALESCE((t1.""其他"")::numeric, (0)::numeric) AS ""其他"",
    COALESCE((t2.twotoone)::numeric, (0)::numeric) AS twotoone,
    COALESCE((t2.onetoone)::numeric, (0)::numeric) AS onetoone,
    COALESCE((t2.tzzfybjcdssjk)::numeric, (0)::numeric) AS tzzfybjcdssjk,
    COALESCE(t2.wwcbjssyjbjwcsj, (0)::numeric) AS wwcbjssyjbjwcsj
   FROM (( SELECT count(1) AS zcount,
            t1_1.xzq,
            t1_1.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%单插口%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (t1_1.xzqdm)::text)) AS ""单插口"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%集中充电桩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (t1_1.xzqdm)::text)) AS ""集中充电桩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%充(换)电柜%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (t1_1.xzqdm)::text)) AS ""充(换)电柜"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%单仓%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (t1_1.xzqdm)::text)) AS ""单仓"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%其他%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.xzqdm)::text = (t1_1.xzqdm)::text)) AS ""其他""
           FROM  zm_buildings t1_1
          WHERE fwbh not in  (select fwbh From  {table_name} where final_create_on='{time}'  and final_fwzt is not null  )
          GROUP BY t1_1.xzqdm, t1_1.xzq
          ORDER BY t1_1.xzqdm) t1
     LEFT JOIN ( SELECT sum(zm_pc_gjzz_cj.qcxycdjk) AS qcxycdjk,
            sum(zm_pc_gjzz_cj.xfctdsl) AS xfctdsl,
            sum(zm_pc_gjzz_cj.abzjsxfscsl) AS abzjsxfscsl,
            sum(zm_pc_gjzz_cj.pzxfsb) AS pzxfsb,
            sum(zm_pc_gjzz_cj.sfjszzxfdhxxxfz) AS sfjszzxfdhxxxfz,
            sum(zm_pc_gjzz_cj.twotoone) AS twotoone,
            sum(zm_pc_gjzz_cj.onetoone) AS onetoone,
            sum(zm_pc_gjzz_cj.tzzfybjcdssjk) AS tzzfybjcdssjk,
            sum((zm_pc_gjzz_cj.wwcbjssyjbjwcsj)::numeric) AS wwcbjssyjbjwcsj,
            zm_pc_gjzz_cj.xzq,
            zm_pc_gjzz_cj.xzqdm
           FROM zm_pc_gjzz_cj
          GROUP BY zm_pc_gjzz_cj.xzqdm, zm_pc_gjzz_cj.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text)))
  ORDER BY t1.xzqdm)gjzz1gqview 
   ";
                    #endregion
                }
                
                else if (RegionCode.Length == 6)
                {
                    #region
                    sql = $@"  	  	  	
	SELECT
	town,
	towndm,
	xzq,
	xzqdm,
	qcxycdjk,xfctdsl,abzjsxfscsl+pzxfsb as abzjsxfscsl,pzxfsb,sfjszzxfdhxxxfz,twotoone,onetoone,tzzfybjcdssjk,wwcbjssyjbjwcsj,""单插口"",""集中充电桩"",""充(换)电柜"",""单仓"",""其他""
FROM
	( SELECT t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE((t2.qcxycdjk)::numeric, (0)::numeric) AS qcxycdjk,
    COALESCE((t2.xfctdsl)::numeric, (0)::numeric) AS xfctdsl,
    COALESCE((t2.abzjsxfscsl)::numeric, (0)::numeric) AS abzjsxfscsl,
    COALESCE((t2.pzxfsb)::numeric, (0)::numeric) AS pzxfsb,
    COALESCE((t2.sfjszzxfdhxxxfz)::numeric, (0)::numeric) AS sfjszzxfdhxxxfz,
    COALESCE((t1.""单插口"")::numeric, (0)::numeric) AS ""单插口"",
    COALESCE((t1.""集中充电桩"")::numeric, (0)::numeric) AS ""集中充电桩"",
    COALESCE((t1.""充(换)电柜"")::numeric, (0)::numeric) AS ""充(换)电柜"",
    COALESCE((t1.""单仓"")::numeric, (0)::numeric) AS ""单仓"",
    COALESCE((t1.""其他"")::numeric, (0)::numeric) AS ""其他"",
    COALESCE((t2.twotoone)::numeric, (0)::numeric) AS twotoone,
    COALESCE((t2.onetoone)::numeric, (0)::numeric) AS onetoone,
    COALESCE((t2.tzzfybjcdssjk)::numeric, (0)::numeric) AS tzzfybjcdssjk,
    COALESCE(t2.wwcbjssyjbjwcsj, (0)::numeric) AS wwcbjssyjbjwcsj
   FROM ((( SELECT count(1) AS zcount,
            t1_1.xzq,
            t1_1.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%单插口%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (t1_1.towndm)::text)) AS ""单插口"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%集中充电桩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (t1_1.towndm)::text)) AS ""集中充电桩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%充(换)电柜%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (t1_1.towndm)::text)) AS ""充(换)电柜"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%单仓%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.town)::text = (t1_1.towndm)::text)) AS ""单仓"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%其他%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.towndm)::text = (t1_1.towndm)::text)) AS ""其他"",
            t1_1.towndm
           FROM zm_buildings t1_1
          WHERE fwbh not in (select fwbh From  {table_name} where final_create_on='{time}'  and final_fwzt is not null  )
          GROUP BY t1_1.xzq, t1_1.xzqdm, t1_1.towndm
          ORDER BY t1_1.towndm) t1
     LEFT JOIN ( SELECT sum(zm_pc_gjzz_cj.qcxycdjk) AS qcxycdjk,
            sum(zm_pc_gjzz_cj.xfctdsl) AS xfctdsl,
            sum(zm_pc_gjzz_cj.abzjsxfscsl) AS abzjsxfscsl,
            sum(zm_pc_gjzz_cj.pzxfsb) AS pzxfsb,
            sum(zm_pc_gjzz_cj.sfjszzxfdhxxxfz) AS sfjszzxfdhxxxfz,
            sum(zm_pc_gjzz_cj.twotoone) AS twotoone,
            sum(zm_pc_gjzz_cj.onetoone) AS onetoone,
            sum(zm_pc_gjzz_cj.tzzfybjcdssjk) AS tzzfybjcdssjk,
            sum((zm_pc_gjzz_cj.wwcbjssyjbjwcsj)::numeric) AS wwcbjssyjbjwcsj,
            zm_pc_gjzz_cj.town,
            zm_pc_gjzz_cj.towndm
           FROM zm_pc_gjzz_cj
          GROUP BY zm_pc_gjzz_cj.town, zm_pc_gjzz_cj.towndm) t2 ON (((t1.towndm)::text = (t2.towndm)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
  ORDER BY t1.towndm)gjzz2xzview
where xzqdm='" + RegionCode + "'";
                    #endregion
                }
                else if (RegionCode.Length == 12)
                {
                    #region
                    sql = $@" 
    SELECT
	town,
	towndm,
	xzq,
	xzqdm,
	village,
	villagedm,
qcxycdjk,xfctdsl,abzjsxfscsl+pzxfsb as abzjsxfscsl,pzxfsb,sfjszzxfdhxxxfz,twotoone,onetoone,tzzfybjcdssjk,wwcbjssyjbjwcsj,""单插口"",""集中充电桩"",""充(换)电柜"",""单仓"",""其他""
FROM
	( SELECT t4.region_name AS village,
    t1.villagedm,
    t1.xzq,
    t1.xzqdm,
    t3.region_name AS town,
    t1.towndm,
    COALESCE((t1.zcount)::numeric, (0)::numeric) AS zcount,
    COALESCE((t2.qcxycdjk)::numeric, (0)::numeric) AS qcxycdjk,
    COALESCE((t2.xfctdsl)::numeric, (0)::numeric) AS xfctdsl,
    COALESCE((t2.abzjsxfscsl)::numeric, (0)::numeric) AS abzjsxfscsl,
    COALESCE((t2.pzxfsb)::numeric, (0)::numeric) AS pzxfsb,
    COALESCE((t1.""单插口"")::numeric, (0)::numeric) AS ""单插口"",
    COALESCE((t2.sfjszzxfdhxxxfz)::numeric, (0)::numeric) AS sfjszzxfdhxxxfz,
    COALESCE((t1.""集中充电桩"")::numeric, (0)::numeric) AS ""集中充电桩"",
    COALESCE((t1.""充(换)电柜"")::numeric, (0)::numeric) AS ""充(换)电柜"",
    COALESCE((t1.""单仓"")::numeric, (0)::numeric) AS ""单仓"",
    COALESCE((t1.""其他"")::numeric, (0)::numeric) AS ""其他"",
    COALESCE((t2.twotoone)::numeric, (0)::numeric) AS twotoone,
    COALESCE((t2.onetoone)::numeric, (0)::numeric) AS onetoone,
    COALESCE((t2.tzzfybjcdssjk)::numeric, (0)::numeric) AS tzzfybjcdssjk,
    COALESCE(t2.wwcbjssyjbjwcsj, (0)::numeric) AS wwcbjssyjbjwcsj
   FROM (((( SELECT count(1) AS zcount,
            t1_1.villagedm,
            t1_1.xzq,
            t1_1.xzqdm,
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%单插口%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (t1_1.villagedm)::text)) AS ""单插口"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%集中充电桩%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (t1_1.villagedm)::text)) AS ""集中充电桩"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%充(换)电柜%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (t1_1.villagedm)::text)) AS ""充(换)电柜"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%单仓%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (t1_1.villagedm)::text)) AS ""单仓"",
            ( SELECT sum(
                        CASE
                            WHEN ((zm_pc_base.cdfs)::text ~~ '%其他%'::text) THEN 1
                            ELSE 0
                        END) AS sum
                   FROM zm_pc_base
                  WHERE ((zm_pc_base.village)::text = (t1_1.villagedm)::text)) AS ""其他"",
            t1_1.towndm
           FROM zm_buildings t1_1
          WHERE fwbh not in (select fwbh From  {table_name} where final_create_on='{time}'  and final_fwzt is not null  )
          GROUP BY t1_1.villagedm, t1_1.xzq, t1_1.xzqdm, t1_1.towndm
          ORDER BY t1_1.villagedm) t1
     LEFT JOIN ( SELECT sum(zm_pc_gjzz_cj.qcxycdjk) AS qcxycdjk,
            sum(zm_pc_gjzz_cj.xfctdsl) AS xfctdsl,
            sum(zm_pc_gjzz_cj.abzjsxfscsl) AS abzjsxfscsl,
            sum(zm_pc_gjzz_cj.pzxfsb) AS pzxfsb,
            sum(zm_pc_gjzz_cj.sfjszzxfdhxxxfz) AS sfjszzxfdhxxxfz,
            sum(zm_pc_gjzz_cj.twotoone) AS twotoone,
            sum(zm_pc_gjzz_cj.onetoone) AS onetoone,
            sum(zm_pc_gjzz_cj.tzzfybjcdssjk) AS tzzfybjcdssjk,
            sum((zm_pc_gjzz_cj.wwcbjssyjbjwcsj)::numeric) AS wwcbjssyjbjwcsj,
            zm_pc_gjzz_cj.villagedm,
            zm_pc_gjzz_cj.towndm,
            zm_pc_gjzz_cj.xzq,
            zm_pc_gjzz_cj.xzqdm
           FROM zm_pc_gjzz_cj
          GROUP BY zm_pc_gjzz_cj.villagedm, zm_pc_gjzz_cj.towndm, zm_pc_gjzz_cj.xzq, zm_pc_gjzz_cj.xzqdm) t2 ON (((t1.villagedm)::text = (t2.villagedm)::text)))
     LEFT JOIN zm_department t3 ON (((t1.towndm)::text = (t3.id)::text)))
     LEFT JOIN zm_department t4 ON (((t1.villagedm)::text = (t4.id)::text)))
  ORDER BY t1.villagedm)gjzz3cjview
where towndm='" + RegionCode + "'";
                }
                #endregion
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, null).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }

        #endregion  中间列结束

        #region 第3列右侧列



        /// <summary>
        /// 隐患覆盖率
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_31fgv")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> dp_31fgv([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                string sql = "";
                string RegionCode = param.code;
                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                if (!string.IsNullOrWhiteSpace(RegionCode))
                {
                    RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                }

                string tablename = "zm_building_fwzt_" + param.endtime.Year;
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                string starttime = Convert.ToDateTime(param.startime + "").ToString("yyyy-MM-dd");
                string endtime = Convert.ToDateTime(param.endtime + "").ToString("yyyy-MM-dd");

     
                string strtype = "z";
                string strtypezd = "zc";
                string strtypezdl2 = "";
                if (param.type == "1")
                {
                    strtype = "z";
                    strtypezd = "zcl";
                    strtypezdl2 = "zcl";
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(xzq, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(xzqdm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezd + "2 AS VARCHAR), ', ' ), ']') " + strtypezdl2 + "  from  ( select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from   zcqkgqtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa 	order by  CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   desc  ) as aa ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(town, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(towndm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezd + "2 AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  (  select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from  zcqkxztext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa  where xzqdm like ('%" + param.code + "%')  	order by  CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   desc ) as aa";
                    }
                    else if (RegionCode.Length == 12)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(village, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(villagedm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezd + "2 AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  (  select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from  zcqkcjtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename +"')) as aa  where towndm like  ('%" + param.code + "%') 	order by  CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   desc) as aa ";
                    }
                }
                else
                {
                    strtype = "j";
                    strtypezd = "jcl";
                    strtypezdl2 = "zcl";
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(xzq, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(xzqdm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezd + "2 AS VARCHAR), ', ' ), ']') " + strtypezdl2 + "  from  ( select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from  jcqkgqtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa 	order by  CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   desc  ) as aa ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(town, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(towndm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezd + "2 AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  (  select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from  jcqkxztext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','"+param.code+"','" + tablename + "')) as aa  where xzqdm like ('%" + param.code + "%')  	order by  CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   desc ) as aa";
                    }
                    else if (RegionCode.Length == 12)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(village, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(villagedm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezd + "2 AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  (  select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from  jcqkcjtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','"+param.code+"','" + tablename + "')) as aa  where towndm like  ('%" + param.code + "%') 	order by  CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   desc) as aa ";
                    }
                }

                //优化转
                var data = _dbContext.Database.GetDbConnection().Query<dynamic>(sql, new { starttime = param.startime, tablename = tablename, code = "%" + RegionCode + "%" }).FirstOrDefault();
                if (data != null)
                {
                    var dictionary = ((IDictionary<string, object>)data).ToDictionary(kvp => kvp.Key, kvp =>
                    {
                        var stringList = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        return stringList.ToList();
                    });

                    var response = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/dp_21zcjc", response);
                    return response;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/dp_31fgv", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/dp_31fgv", res);
                res.Msg = "系统异常" + ex.Message;
                return res;
            }
        }




        /// <summary>
        /// 隐患覆盖率【2级】
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_31fgv2jhc")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> dp_31fgv2jhc([FromBody] DateQuery param)
        {
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                string sql = "";
                string RegionCode = param.code;
                if (!string.IsNullOrWhiteSpace(RegionCode))
                {
                    RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                }
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                string starttime = Convert.ToDateTime(param.startime + "").ToString("yyyy-MM-dd");
                string endtime = Convert.ToDateTime(param.endtime + "").ToString("yyyy-MM-dd");
                string tablename = "";
                string filed = "";
                string fileWhere = "";
                string strtype = "z";
                string strtypezd = "zcl";
                if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                {
                    sql = @"              select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from  hcqkgqtext_fz(  '" + param.startime + "','" + param.endtime + "',@yhly)) as aa 	order by  CAST(REPLACE(" + strtype + "cl, '%', '') AS DECIMAL(18, 2))   desc   ";
                }
                else if (RegionCode.Length == 6)
                {
                    sql = @"  	  	  	  select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from hcqkxztext_fz( '" + param.startime + "','" + param.endtime + "',@yhly)) as aa  where xzqdm like ('" + param.code + "%')  	order by  CAST(REPLACE(" + strtype + "cl, '%', '') AS DECIMAL(18, 2))   desc ";
                }
                else if (RegionCode.Length == 12 || RegionCode.Length == 9)
                {
                    sql = @"  	  	  	  select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from hcqkcjtext_fz( '" + param.startime + "','" + param.endtime + "',@yhly)) as aa  where towndm like  ('" + param.code + "%') 	order by  CAST(REPLACE(" + strtype + "cl, '%', '') AS DECIMAL(18, 2))   desc ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { starttime = param.startime, tablename = tablename, code = "%" + RegionCode + "%", @yhly = param.hctype }).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }
        /// <summary>
        /// 隐患覆盖率【2级】
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_31fgv2j")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> dp_31fgv2j([FromBody] DateQuery param)
        {
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                string tablename = "zm_building_fwzt_" + param.endtime.Year;
                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                string sql = "";
                string RegionCode = param.code;
                if (!string.IsNullOrWhiteSpace(RegionCode))
                {
                    RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                }
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                string starttime = Convert.ToDateTime(param.startime + "").ToString("yyyy-MM-dd");
                string endtime = Convert.ToDateTime(param.endtime + "").ToString("yyyy-MM-dd");

                if (param.type == "1")
                {
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @" select * from  zcqkgqtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')        ORDER BY  COALESCE(zccount/case when zcount=0 then null else zcount end,0) desc  ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @" select * from   zcqkxztext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "') where towndm like @code    ORDER BY COALESCE(zccount/case when zcount=0 then null else zcount end,0) desc  ";
                    }
                    else if (RegionCode.Length == 12 || RegionCode.Length == 9)
                    {
                        sql = @" select * from  zcqkcjtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "') where villagedm like @code    ORDER BY COALESCE(zccount/case when zcount=0 then null else zcount end,0) desc  ";
                    }
                }
                else
                {
                    string strtype = "j";
                    string strtypezd = "jcl";

                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @"              select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from  jcqkgqtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "') ) as aa 	order by  CAST(REPLACE(" + strtype + "cl, '%', '') AS DECIMAL(18, 2))   desc   ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @"  	  	  	  select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from jcqkxztext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','"+param.code+"','" + tablename + "')) as aa  where xzqdm like ('%" + param.code + "%')  	order by  CAST(REPLACE(" + strtype + "cl, '%', '') AS DECIMAL(18, 2))   desc ";
                    }
                    else if (RegionCode.Length == 12 || RegionCode.Length == 9)
                    {
                        sql = @"  	  	  	  select  * from( select *, CAST(REPLACE(" + strtypezd + ", '%', '') AS DECIMAL(18, 2))   as  " + strtypezd + "2  from  jcqkcjtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','"+param.code+"','" + tablename + "')) as aa  where towndm like  ('%" + param.code + "%') 	order by  CAST(REPLACE(" + strtype + "cl, '%', '') AS DECIMAL(18, 2))   desc ";
                    }

                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { starttime = param.startime, tablename = tablename, code = "%" + RegionCode + "%" }).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }

        }

        /// <summary>
        /// 隐患发现率
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_32yhfxl")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> dp_32yhfxl([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                string sql = "";
                string RegionCode = param.code;
                if (!string.IsNullOrWhiteSpace(RegionCode))
                {
                    RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                }
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                string starttime = Convert.ToDateTime(param.startime + "").ToString("yyyy-MM-dd");
                string endtime = Convert.ToDateTime(param.endtime + "").ToString("yyyy-MM-dd");
                string filed = "";
                string fileWhere = "";
                string strtype = "z";
                string strtypezd = "yh";
                string strtypezdl = "yhl";
                string strtypezdl2 = "";

                string tablename = "zm_building_fwzt_" + param.endtime.Year;


                if (param.type == "1")
                {
                    strtypezdl2 = "yhl";
                    strtype = "z";
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(xzq, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(xzqdm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']') " + strtypezdl2 + "  from  ( select  * from( select *,COALESCE( round((" + strtypezd + "count)*1.00*100/(case when zccount=0 then null else zccount end ),2),0)   as  " + strtypezd + "l  from  zcqkgqtext_fz('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa 	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/(case when zccount=0 then null else zccount end ),2),0)   desc) bb  ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(town, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(towndm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  ( select  * from( select *,COALESCE(round((" + strtypezd + "count)*1.00*100/(case when zccount=0 then null else zccount end ),2),0)   as  " + strtypezd + "l   from  zcqkxztext_fz( '" + starttime + " 00:00:00','" + endtime + " 23:59:59',@code,'" + tablename +"')) as aa  where xzqdm like ('" + param.code + "%')  	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/(case when zccount=0 then null else zccount end ),2),0)   desc) bb ";
                    }
                    else if (RegionCode.Length == 12 || RegionCode.Length == 9)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(village, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(villagedm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  ( select  * from( select *,COALESCE(round((" + strtypezd + "count)*1.00*100/(case when zccount=0 then null else zccount end ),2),0)   as  " + strtypezd + "l  from  zcqkcjtext_fz('" + starttime + " 00:00:00','" + endtime + " 23:59:59',@code,'" + tablename + "')) as aa  where towndm like  ('" + param.code + "%') 	order by COALESCE(round((" + strtypezd + "count)*1.00*100/(case when zccount=0 then null else zccount end ),2),0)   desc)bb ";
                    }
                }
                else
                {
                    strtypezdl2 = "yhl";
                    strtype = "j";
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(xzq, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(xzqdm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']') " + strtypezdl2 + "  from  ( select  * from( select *, COALESCE(round((" + strtypezd + "count)*1.00*100/(case when  jccount=0 then null else jccount end),2),0)   as  " + strtypezd + "l  from   jcqkgqtext_fz('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa 	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/(case when  jccount=0 then null else jccount end),2),0)   desc) bb  ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(town, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(towndm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  ( select  * from( select *, COALESCE(round((" + strtypezd + "count)*1.00*100/(case when  jccount=0 then null else jccount end),2),0) as  " + strtypezd + "l   from    jcqkxztext_fz('" + starttime + " 00:00:00','" + endtime + " 23:59:59',@code,'" + tablename + "')) as aa  where xzqdm like ('" + param.code + "%')  	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/(case when  jccount=0 then null else jccount end),2),0)  desc) bb ";
                    }
                    else if (RegionCode.Length == 12)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(village, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(villagedm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  ( select  * from( select *, COALESCE(round((" + strtypezd + "count)*1.00*100/(case when  jccount=0 then null else jccount end),2),0)   as  " + strtypezd + "l  from  jcqkcjtext_fz('" + starttime + " 00:00:00','" + endtime + " 23:59:59',@code,'" + tablename + "')) as aa  where towndm like  ('" + param.code + "%') 	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/(case when  jccount=0 then null else jccount end),2),0)   desc)bb ";
                    }
                }


                //优化转
                var data = _dbContext.Database.GetDbConnection().Query<dynamic>(sql, new { starttime = param.startime, tablename = tablename, code = "%" + RegionCode + "%" }).FirstOrDefault();
                if (data != null)
                {
                    var dictionary = ((IDictionary<string, object>)data).ToDictionary(kvp => kvp.Key, kvp =>
                    {
                        var stringList = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        return stringList.ToList();
                    });

                    var response = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/dp_32yhfxl", response);
                    return response;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/dp_32yhfxl", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/dp_32yhfxl", res);
                res.Msg = "系统异常";
                return res;
            }
        }
        /// <summary>
        /// 隐患发现率【2级】
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_32yhfxl2j")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> dp_32yhfxl2j([FromBody] DateQuery param)
        {
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                string sql = "";
                string RegionCode = param.code;
                if (!string.IsNullOrWhiteSpace(RegionCode))
                {
                    RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                }
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                string starttime = Convert.ToDateTime(param.startime + "").ToString("yyyy-MM-dd");
                string endtime = Convert.ToDateTime(param.endtime + "").ToString("yyyy-MM-dd");
                string tablename = "zm_building_fwzt_" + param.endtime.Year;

                string filed = "";
                string fileWhere = "";

                if (param.type == "1")
                {
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @" select *,COALESCE(round(yhcount*100.00/case when zccount= 0 then null else zccount end,2),0)||'%' yhl from  zcqkgqtext_fz(@starttime,'" + endtime + " 23:59:59',@tablename)  ORDER BY COALESCE(round(yhcount*100/case when zccount= 0 then null else zccount end,2),0) desc  ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @" select *,COALESCE(round(yhcount*100.00/case when zccount= 0 then null else zccount end,2),0)||'%' yhl from  zcqkxztext_fz(@starttime,'" + endtime + " 23:59:59',@code,@tablename) where towndm like @code  ORDER BY COALESCE(round(yhcount*100/case when zccount= 0 then null else zccount end,2),0) desc  ";
                    }
                    else if (RegionCode.Length == 12 || RegionCode.Length == 9)

                    {
                        sql = @" select *,COALESCE(round(yhcount*100.00/case when zccount= 0 then null else zccount end,2),0)||'%' yhl from  zcqkcjtext_fz(@starttime,'" + endtime + " 23:59:59',@code,@tablename) where villagedm like @code  ORDER BY  COALESCE(round(yhcount*100/case when zccount= 0 then null else zccount end,2),0) desc  ";
                    }
                }
                else
                {
                    string strtype = "j";
                    string strtypezd = "yh";

                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
 
                        sql = @" 	  select  *,jccount jccount from( select *, COALESCE(round(yhcount*100.00/case when jccount= 0 then null else jccount end,2),0)||'%' yhl from  jcqkgqtext_fz('"+ @starttime+"','" + endtime + " 23:59:59',@tablename)) as aa 	ORDER BY COALESCE(round(yhcount*100/case when jccount= 0 then null else jccount end,2),0) desc ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @" 	  select  *,jccount jccount from( select *, COALESCE(round(yhcount*100.00/case when jccount= 0 then null else jccount end,2),0)||'%' yhl from  jcqkxztext_fz('"+ @starttime+"','" + endtime + " 23:59:59',@code,@tablename)) as aa	where towndm like @code ORDER BY COALESCE(round(yhcount*100/case when jccount= 0 then null else jccount end,2),0) desc";

                    }
                    else if (RegionCode.Length == 12 || RegionCode.Length == 9)
                    {
                        sql = @" 	  select  *,jccount jccount from( select *,  COALESCE(round(yhcount*100.00/case when jccount= 0 then null else jccount end,2),0)||'%' yhl from  jcqkcjtext_fz('"+ @starttime+"','" + endtime + " 23:59:59',@code,@tablename)) as aa	where villagedm like @code ORDER BY COALESCE(round(yhcount*100/case when jccount= 0 then null else jccount end,2),0) desc";
                    }

                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { starttime = param.startime, tablename = tablename, code = "%" + RegionCode + "%" }).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 隐患整改率
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_33yhzgl")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> dp_33yhzgl([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                string sql = "";
                string RegionCode = param.code;
                if (!string.IsNullOrWhiteSpace(RegionCode))
                {
                    RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                }
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                string starttime = Convert.ToDateTime(param.startime + "").ToString("yyyy-MM-dd");
                string endtime = Convert.ToDateTime(param.endtime + "").ToString("yyyy-MM-dd");
                string filed = "";
                string fileWhere = "";


                string strtype = "z";
                string strtypezd = "zg";
                string strtypezdl = "zgl";
                string strtypezdl2 = "";

                string tablename = "zm_building_fwzt_" + param.endtime.Year;




                if (param.type == "1")
                {

                    strtypezdl2 = "zgl";
                    strtype = "z";
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(xzq, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(xzqdm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']') " + strtypezdl2 + "  from  ( select  * from( select *,COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   as  " + strtypezd + "l  from  zcqkgqtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa 	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   desc) bb  ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(town, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(towndm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  ( select  * from( select *, COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   as  " + strtypezd + "l   from zcqkxztext( '" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa  where xzqdm like ('" + param.code + "%')  	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   desc) bb ";
                    }
                    else if (RegionCode.Length == 12)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(village, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(villagedm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  ( select  * from( select *,COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   as  " + strtypezd + "l  from zcqkcjtext( '" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa  where towndm like  ('" + param.code + "%') 	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   desc) bb ";
                    }
                }
                else
                {
                    strtypezdl2 = "zgl";
                    strtype = "j";
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(xzq, '区','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(xzqdm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']') " + strtypezdl2 + "  from  ( select  * from( select *,COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   as  " + strtypezd + "l  from  jcqkgqtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa 	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   desc) bb  ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(town, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(towndm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  ( select  * from( select *, COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   as  " + strtypezd + "l   from  jcqkxztext( '" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa  where xzqdm like ('" + param.code + "%')  	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   desc) bb ";
                    }
                    else if (RegionCode.Length == 12)
                    {
                        sql = @"select CONCAT('[', STRING_AGG(CAST( replace(village, '','') AS VARCHAR), ', ' ), ']') name,CONCAT('[', STRING_AGG(CAST(villagedm AS VARCHAR), ', ' ), ']') code,CONCAT('[', STRING_AGG(CAST(" + strtypezdl + " AS VARCHAR), ', ' ), ']')  " + strtypezdl2 + " from  ( select  * from( select *, COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   as  " + strtypezd + "l  from  jcqkcjtext('" + starttime + " 00:00:00','" + endtime + " 23:59:59','" + tablename + "')) as aa  where towndm like  ('" + param.code + "%') 	order by COALESCE(round((" + strtypezd + "count)*1.00*100/((case when yhcount=0 then null else yhcount end)),2),0)   desc) bb ";
                    }
                }



                //优化转
                var data = _dbContext.Database.GetDbConnection().Query<dynamic>(sql, new { starttime = param.startime, tablename = tablename, code = "%" + RegionCode + "%" }).FirstOrDefault();
                if (data != null)
                {
                    var dictionary = ((IDictionary<string, object>)data).ToDictionary(kvp => kvp.Key, kvp =>
                    {
                        var stringList = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        return stringList.ToList();
                    });

                    var response = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/dp_33yhzgl", response);
                    return response;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/dp_33yhzgl", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/dp_33yhzgl", res);
                res.Msg = "系统异常";
                return res;
            }
        }
        /// <summary>
        /// 隐患整改率【2级】
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_33yhzgl2j")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> dp_33yhzgl2j([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }
                string sql = "";
                string RegionCode = param.code;

                string strtype = "z";
                string strtypezd = "zg";
                if (!string.IsNullOrWhiteSpace(RegionCode))
                {
                    RegionCode = RegionCode.Substring(RegionCode.Length - 3) == "000" ? RegionCode.Substring(0, RegionCode.Length - 3) : RegionCode;
                }
                string today = DateTime.Now.ToString("yyyy-MM-dd");
                string starttime = Convert.ToDateTime(param.startime + "").ToString("yyyy-MM-dd");
                string endtime = Convert.ToDateTime(param.endtime + "").ToString("yyyy-MM-dd");
                string filed = "";
                string fileWhere = "";
                string tablename = "zm_building_fwzt_" + param.endtime.Year;


                if (param.type == "1")
                {
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @" select *,COALESCE(round(zgcount*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)||'%' zgl from  zcqkgqtext(@starttime,'" + endtime + " 23:59:59',@tablename)  ORDER BY COALESCE(round(zgcount*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)   desc  ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @" select *,COALESCE(round(zgcount*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)||'%' zgl from  zcqkxztext(@starttime,'" + endtime + " 23:59:59',@tablename)  where towndm like @code ORDER BY COALESCE(round(zgcount*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)   desc  ";
                    }
                    else if (RegionCode.Length == 12 || RegionCode.Length == 9)
                    {
                        sql = @" select *,COALESCE(round(zgcount*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)||'%' zgl from  zcqkcjtext(@starttime,'" + endtime + " 23:59:59',@tablename) where villagedm like @code order by COALESCE(round(zgcount*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)   desc  ";
                    }
                }
                else
                {
                    strtype = "j";
                    if (RegionCode == null || string.IsNullOrEmpty(RegionCode) || RegionCode.Length == 3)
                    {
                        sql = @"   	 	  	  select  * from( select *,COALESCE(round((" + strtypezd + "count)*1.00*100/(case when yhcount=0 then null else yhcount end),2),0.00)|| '%'    as  " + strtypezd + "l  from  jcqkgqtext( @starttime,'" + endtime + " 23:59:59',@tablename)) as aa 	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)   desc   ";
                    }
                    else if (RegionCode.Length == 6)
                    {
                        sql = @"  	  	  	  select  * from( select *, COALESCE(round((" + strtypezd + "count)*1.00*100/(case when yhcount=0 then null else yhcount end),2),0.00)|| '%'    as  " + strtypezd + "l   from jcqkxztext(@starttime,'" + endtime + " 23:59:59',@code,@tablename)) as aa  where xzqdm like ('%" + param.code + "%')  	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)   desc ";
                    }
                    else if (RegionCode.Length == 12 || RegionCode.Length == 9)
                    {
                        sql = @"  	  	  	  select  * from( select *,COALESCE(round((" + strtypezd + "count)*1.00*100/(case when yhcount=0 then null else yhcount end),2),0.00)|| '%'    as  " + strtypezd + "l  from  jcqkcjtext(@starttime,'" + endtime + " 23:59:59',@code,@tablename)) as aa  where towndm like  ('%" + param.code + "%') 	order by  COALESCE(round((" + strtypezd + "count)*1.00*100/(case when yhcount=0 then null else yhcount end),2),0)   desc ";
                    }
                }

                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { starttime = param.startime, tablename = tablename, code = "%" + RegionCode + "%" }).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }

        /// <summary>
        /// 隐患类型分析(不分自查检查，不传类型)
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_34yhlxf")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> dp_34yhlxf([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {

                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<object>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime = DateTime.Today;
                }


                param.endtime = param.endtime.AddDays(1).AddSeconds(-1);
                string sql = "";
                string RegionCode = param.code;
                string strtypetable = "";
                string formattedDate = param.endtime.ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + param.endtime.Year;
                if (RegionCode == null || string.IsNullOrEmpty(RegionCode))
                {
                    sql = @"
-- 整合两个表的数据并计算总值
WITH CombinedData AS (
    SELECT 
        '私拉乱接电线' AS name, 
        SUM(slljdx) AS total_count
    FROM  
        (
            SELECT slljdx
            FROM  z_jcyhgq('" + param.startime + "','" + formattedDate +"','" + table_name + @"')
            UNION ALL
            SELECT slljdx
            FROM  z_zcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
        ) AS t1
    UNION ALL
    SELECT 
        '烟感报警器未保持完好有效' AS name, 
        SUM(ygbjwfwhyx) AS total_count
    FROM  
        (
            SELECT ygbjwfwhyx
            FROM  z_jcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
            UNION ALL
            SELECT ygbjwfwhyx
            FROM  z_zcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
        ) AS t2
    UNION ALL
    SELECT 
        '影响人员疏散的堆放物品' AS name, 
        SUM(use_stacked_items) AS total_count
    FROM  
        (
            SELECT use_stacked_items
            FROM  z_jcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
            UNION ALL
            SELECT use_stacked_items
            FROM  z_zcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
        ) AS t3
    UNION ALL
    SELECT 
        '灭火器未保持完好有效' AS name, 
        SUM(mhqwbcwhyx) AS total_count
    FROM  
        (
            SELECT mhqwbcwhyx
            FROM  z_jcyhgq('" + param.startime + "','" + formattedDate +"','" + table_name + @"')
            UNION ALL
            SELECT mhqwbcwhyx
            FROM  z_zcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
        ) AS t4
    UNION ALL
    SELECT 
        '室内停放、充电电动车数量' AS name, 
        SUM(use_electric_bicycle) AS total_count
    FROM  
        (
            SELECT use_electric_bicycle
            FROM  z_jcyhgq('" + param.startime + "','" + formattedDate +"','" + table_name + @"')
            UNION ALL
            SELECT use_electric_bicycle
            FROM  z_zcyhgq('" + param.startime + "','" + formattedDate +"','" + table_name + @"')
        ) AS t5
    UNION ALL
    SELECT 
        '使用瓶装液化石油气数量' AS name, 
        SUM(use_bottled_liquefied_gas) AS total_count
    FROM  
        (
            SELECT use_bottled_liquefied_gas
            FROM  z_jcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
            UNION ALL
            SELECT use_bottled_liquefied_gas
            FROM  z_zcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
        ) AS t6
    UNION ALL
    SELECT 
        '简易喷淋灭火系统未保持完好有效' AS name, 
        SUM(jyplmhxtwbcwhyx) AS total_count
    FROM  
        (
            SELECT jyplmhxtwbcwhyx
            FROM  z_jcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
            UNION ALL
            SELECT jyplmhxtwbcwhyx
            FROM  z_zcyhgq('" + param.startime + "','" + formattedDate + "','" + table_name + @"')
        ) AS t7
),
-- 计算总值和每一项的百分比
TotalCounts AS (
    SELECT SUM(total_count) AS total_sum
    FROM CombinedData
)
-- 计算每一项和其他六项合并后的百分比
SELECT 
    name,   
   COALESCE(ROUND((SUM(total_count) / (SELECT case when total_sum=0 then null else total_sum end FROM TotalCounts)) * 100, 2),0) AS percentage_total_count
FROM CombinedData
GROUP BY name

 ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, null).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                //WriteSystemLog(usernNumber, "houses/dp_33yhzgl", res);
                res.Msg = "系统异常";
                return res;
            }
        }

        #endregion 第3列右侧




        /// <summary>
        /// 隐患类型分析详情（点击统计下钻到隐患详情）
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_34yhlxf_yh")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<Page<object>> dp_34yhlxf_yh([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<Page<object>>(false, "请传递时间");
                }

                if (param.endtime > DateTime.Now)
                {
                    param.endtime= DateTime.Today;
                }
                if (string.IsNullOrWhiteSpace(param.yhlx))
                {
                    return new RespRet<Page<object>>(false, "请传递隐患类型");
                }
                param.endtime = param.endtime.AddHours(23);
                param.endtime = param.endtime.AddMinutes(59);
                param.endtime = param.endtime.AddSeconds(59);
                string sql = ""; string sqlcount = "";
                string RegionCode = param.code;
                string sqlwhere = "";
                if (!string.IsNullOrWhiteSpace(param.xzqdm))
                {
                    sqlwhere += " and b.xzqdm like @xzqdm ";
                }
                if (!string.IsNullOrWhiteSpace(param.towndm))
                {
                    sqlwhere += " and b.towndm like @towndm ";
                }
                if (!string.IsNullOrWhiteSpace(param.villagedm))
                {
                    sqlwhere += " and b.villagedm like @villagedm ";
                }
                string formattedDate = param.endtime.ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + param.endtime.Year;
                if (RegionCode == null || string.IsNullOrEmpty(RegionCode))
                {
                    sql = $@" 
select b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh,b.address,b.hzxm,check_id,check_name,count(1) fxcs from  
( SELECT b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name                  
        FROM zm_pc_yhlog_dx_cj a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  )  and   check_id=@yhlx  {sqlwhere}
union all
SELECT b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name                  
        FROM zm_pc_yhlog_dx a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx  {sqlwhere}
union all
SELECT b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name               
        FROM zm_pc_yhlog_dx_sqjz a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and   check_id=@yhlx  {sqlwhere}
) b GROUP BY  b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh,b.address,b.hzxm,check_id,check_name  order by fwbh limit @limit offset @offset
 ";
                    sqlcount = $@"select count(1) from (  select count(1) fxcs from  
( SELECT b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name                  
        FROM zm_pc_yhlog_dx_cj a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx  {sqlwhere}
union all
SELECT b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name                  
        FROM zm_pc_yhlog_dx a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx  {sqlwhere}
union all
SELECT b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name               
        FROM zm_pc_yhlog_dx_sqjz a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx  {sqlwhere}
) b GROUP BY  b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh,b.address,b.hzxm,check_id,check_name )a 
 ";
                }
                var count = _dbContext.Database.GetDbConnection().Query<int>(sqlcount, new { starttime = param.startime, endtime = param.endtime, yhlx = param.yhlx, limit = param.Limit, offset = (param.PageIndex - 1) * param.Limit, @xzqdm = "%" + param.xzqdm + "%", @towndm = "%" + param.towndm + "%", @villagedm = "%" + param.villagedm + "%" }).FirstOrDefault();
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { starttime = param.startime, endtime = param.endtime, yhlx = param.yhlx, limit = param.Limit, offset = (param.PageIndex - 1) * param.Limit, @xzqdm = "%" + param.xzqdm + "%", @towndm = "%" + param.towndm + "%", @villagedm = "%" + param.villagedm + "%" }).ToList();

                var res = new RespRet<Page<object>>(true, "ok", new Page<object> { Items = data, NextPageIndex = param.PageIndex + 1, PageSize = param.Limit, Total = count, PageTotal = (int)Math.Ceiling(count / (double)param.Limit) });
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<Page<object>>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/dp_34yhlxf_yh", res);
                res.Msg = "系统异常";
                return res;
            }
        }



        /// <summary>
        /// 隐患类型分析详情（点击统计下钻到隐患详情）
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("houses/dp_34yhlxf_allyh")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<Page<object>> dp_34yhlxf_allyh([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null || param.startime == DateTime.MinValue || param.endtime == DateTime.MinValue)
                {
                    return new RespRet<Page<object>>(false, "请传递时间");
                }
                if (string.IsNullOrWhiteSpace(param.yhlx))
                {
                    return new RespRet<Page<object>>(false, "请传递隐患类型");
                }
                if (string.IsNullOrWhiteSpace(param.fwbh))
                {
                    return new RespRet<Page<object>>(false, "请传递房屋编号");
                }
                param.endtime = param.endtime.AddHours(23);
                param.endtime = param.endtime.AddMinutes(59);
                param.endtime = param.endtime.AddSeconds(59);
                string sql = ""; string sqlcount = "";
                string RegionCode = param.code;
                string sqlwhere = "";
                if (!string.IsNullOrWhiteSpace(param.xzqdm))
                {
                    sqlwhere += " and b.xzqdm like @xzqdm ";
                }
                if (!string.IsNullOrWhiteSpace(param.towndm))
                {
                    sqlwhere += " and b.towndm like @towndm ";
                }
                if (!string.IsNullOrWhiteSpace(param.villagedm))
                {
                    sqlwhere += " and b.villagedm like @villagedm ";
                }
                string formattedDate = param.endtime.ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + param.endtime.Year;
                if (RegionCode == null || string.IsNullOrEmpty(RegionCode))
                {
                    sql = $@" 
select * from ( SELECT  (select base_id from zm_pc_yhlog_cj where id=a.yhlog_id) id, case when jcly ='1' then '村民自查' when  jcly='5' then '村级检查'  when  jcly='4' then '街镇核查' when  jcly='3' then '区级核查' when  jcly='2' then '市级核查'  end jcly,case when zg_value ='1' then '已整改' when zg_value='0' then '未整改' end zg_value,check_nickname,to_char(check_time, 'YYYY-MM-DD HH24:MI:SS') check_time,b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name                  
        FROM zm_pc_yhlog_dx_cj a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on  BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  )  and  check_id=@yhlx and b.fwbh=@fwbh  {sqlwhere}
union all
SELECT  (select base_id from zm_pc_yhlog where id=a.yhlog_id) id, case when jcly ='1' then '村民自查' when  jcly='5' then '村级检查'  when  jcly='4' then '街镇核查' when  jcly='3' then '区级核查' when  jcly='2' then '市级核查'  end jcly,case when zg_value ='1' then '已整改' when zg_value='0' then '未整改' end zg_value,check_nickname,to_char(check_time, 'YYYY-MM-DD HH24:MI:SS') check_time,b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name                  
        FROM zm_pc_yhlog_dx a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx and b.fwbh=@fwbh   {sqlwhere}
union all
SELECT  (select base_id from zm_pc_yhlog_sqjz where id=a.yhlog_id) id, case when jcly ='1' then '村民自查' when  jcly='5' then '村级检查'  when  jcly='4' then '街镇核查' when  jcly='3' then '区级核查' when  jcly='2' then '市级核查'  end jcly,case when zg_value ='1' then '已整改' when zg_value='0' then '未整改' end zg_value,check_nickname,to_char(check_time, 'YYYY-MM-DD HH24:MI:SS') check_time,b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name               
        FROM zm_pc_yhlog_dx_sqjz a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx and b.fwbh=@fwbh  {sqlwhere}
) b  ORDER BY check_time desc limit @limit offset @offset
 ";
                    sqlcount = $@"select count(1) from ( SELECT case when jcly ='1' then '村民自查' when  jcly='5' then '村级检查'  when  jcly='4' then '街镇核查' when  jcly='3' then '区级核查' when  jcly='2' then '市级核查'  end jcly,zg_value,check_nickname,check_time,b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name                  
        FROM zm_pc_yhlog_dx_cj a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on  BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx and b.fwbh=@fwbh  {sqlwhere}
union all
SELECT case when jcly ='1' then '村民自查' when  jcly='5' then '村级检查'  when  jcly='4' then '街镇核查' when  jcly='3' then '区级核查' when  jcly='2' then '市级核查'  end jcly,zg_value,check_nickname,check_time,b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name                  
        FROM zm_pc_yhlog_dx a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx and b.fwbh=@fwbh  {sqlwhere}
union all
SELECT case when jcly ='1' then '村民自查' when  jcly='5' then '村级检查'  when  jcly='4' then '街镇核查' when  jcly='3' then '区级核查' when  jcly='2' then '市级核查'  end jcly,zg_value,check_nickname,check_time,b.xzqdm,b.xzq,b.towndm,b.town,b.village,b.villagedm,b.fwbh ,b.address,b.hzxm,check_id,check_name               
        FROM zm_pc_yhlog_dx_sqjz a  join zm_buildings b on  a.fwbh=b.fwbh
        WHERE a.create_on BETWEEN @starttime AND @endtime and a.fwbh not in  (select fwbh From  {table_name} where final_create_on='{formattedDate}'  and final_fwzt is not null  ) and  check_id=@yhlx and b.fwbh=@fwbh  {sqlwhere}
) b  
 ";
                }
                var count = _dbContext.Database.GetDbConnection().Query<int>(sqlcount, new { starttime = param.startime, endtime = param.endtime, yhlx = param.yhlx, limit = param.Limit, offset = (param.PageIndex - 1) * param.Limit, @fwbh = param.fwbh, @xzqdm = "%" + param.xzqdm + "%", @towndm = "%" + param.towndm + "%", @villagedm = "%" + param.villagedm + "%" }).FirstOrDefault();
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { starttime = param.startime, endtime = param.endtime, yhlx = param.yhlx, limit = param.Limit, offset = (param.PageIndex - 1) * param.Limit, @fwbh = param.fwbh, @xzqdm = "%" + param.xzqdm + "%", @towndm = "%" + param.towndm + "%", @villagedm = "%" + param.villagedm + "%" }).ToList();

                var res = new RespRet<Page<object>>(true, "ok", new Page<object> { Items = data, NextPageIndex = param.PageIndex + 1, PageSize = param.Limit, Total = count, PageTotal = (int)Math.Ceiling(count / (double)param.Limit) });
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<Page<object>>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/dp_34yhlxf_yh", res);
                res.Msg = "系统异常";
                return res;
            }
        }

        #endregion
        #region 基本信息 页
        /// <summary>
        /// 获取经营性自建房数量、租住人口数量、出租房间数量、三层及以上、悬挂固定警示标牌、电动车数量、 电动设施数量、消防车道数量
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkjbxx")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(BuildingJbxx), 200)]
        public RespRet<List<Modelbuilding>> HouseMngJbxx([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 																
			select *from 	(select case when  sum(zccount) is null then 0 else sum(zccount)  end   jyxzjfsl,sum(yhcount) yhcount  from zcqkgqview) a, 
			(select case when sum(zzrs) is null then 0 else sum(zzrs) end zzrksl  ,case when  sum(jzfjs) is null then 0 else sum(jzfjs)end czfjsl,
	  	case when  sum(csjyssl) is null then 0 else sum(csjyssl)end scjys,
			case when  sum(xggdjsbp) is null then 0 else sum(xggdjsbp)end xggdjsbp,
		 case when  sum(bdfwjzrydddzxcsl) is null then 0 else sum(bdfwjzrydddzxcsl)end ddzxcsl
	  	from jbxxgqview) b,( select case when sum(czryrs) is null then 0 else  sum(czryrs) end czryrs from zm_pc_base ) t1

																 ";
                var res = _dbContext.Database.GetDbConnection().Query<BuildingJbxx>(sql).FirstOrDefault();  //一行
                List<Modelbuilding> models = new List<Modelbuilding>();
                Modelbuilding model = new Modelbuilding();

                model.name = "自查数量";
                model.value = res.jyxzjfsl;
                model.unit = "栋";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "隐患数量";
                model.value = res.yhcount;
                model.unit = "个";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "租住人口数量";
                model.value = res.zzrksl;
                model.unit = "人";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "出租房间数量";
                model.value = res.czfjsl;
                model.unit = "间";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "三层及以上";
                model.value = res.scjys;
                model.unit = "栋";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "悬挂固定警示标牌";
                model.value = res.xggdjsbp;
                model.unit = "个";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "电动自行车数量";
                model.value = res.ddzxcsl;
                model.unit = "辆";
                models.Add(model);

                //model = new Modelbuilding();
                //model.name = "电动自行车充电接口数量";
                //model.value = res.ddzxccdjksl;
                //model.unit = "个";
                //models.Add(model);

                //model = new Modelbuilding();
                //model.name = "消防车通道数量";
                //model.value = res.xfctdsl;
                //model.unit = "个";
                //models.Add(model);


                model = new Modelbuilding();
                model.name = "外卖/闪送/代驾人数";
                model.value = res.czryrs;
                model.unit = "人";
                models.Add(model);
                return new RespRet<List<Modelbuilding>>(true, "Ok", models);
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        #region 基本信息 村级
        /// <summary>
        /// 获取村级 检查数量，检查率、隐患发现数量，隐患整改数量，电动自行车清理数量，出租房间数量，租住人口数，外卖/闪送人数
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkjbxxcj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(BuildingJbxx), 200)]
        public RespRet<List<Modelbuilding>> HouseMngJbxx_cj([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 																
SELECT   
    t1.*,  
    t2.czfjsl, 
		t2.zzrs, 
	round(((t1.jcsl / NULLIF(t1.zcount, 0))*100), 2)  AS jcl, 
    t3.ddzxcsl,  
    t4.czryrs  
FROM (  
    SELECT   
        COALESCE(SUM(zcount),0) AS zcount,  
        COALESCE(SUM(jccount),0) AS jcsl,  
        COALESCE(SUM(yhcount),0) AS yhcount,  
        COALESCE(SUM(zgcount),0) AS zgcount,  
        '北京市' AS xzq   
    FROM jcqkgqview  
) t1  
LEFT JOIN (  
    SELECT   
        COALESCE(SUM(jzfjs),0) AS czfjsl,  
        COALESCE(SUM(zzrs),0) AS zzrs,  
        '北京市' AS xzq   
    FROM jcjbxxgqview  
) t2 ON t1.xzq = t2.xzq  
LEFT JOIN (  
    SELECT   
        COALESCE(SUM(qlddzxcsl),0) AS ddzxcsl,  
        '北京市' AS xzq   
    FROM zm_pc_gjzz_cj  
) t3 ON t1.xzq = t3.xzq  
LEFT JOIN (  
    SELECT   
        COALESCE(SUM(czryrs),0) AS czryrs,  
        '北京市' AS xzq   
    FROM zm_pc_base_cj  
) t4 ON t1.xzq = t4.xzq;

 

				 ";
                var res = _dbContext.Database.GetDbConnection().Query<BuildingJbxxjc>(sql).FirstOrDefault();  //一行
                List<Modelbuilding> models = new List<Modelbuilding>();
                Modelbuilding model = new Modelbuilding();

                //检查数量，检查率,隐患发现数量，隐患整改数量，
                model.name = "检查数量";
                model.value = res.jcsl;
                model.unit = "栋";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "检查率";
                model.value = res.jcl;
                model.unit = "%";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "隐患发现数量";
                model.value = res.yhcount;
                model.unit = "个";
                models.Add(model);

                //电动自行车清理数量，出租房间数量，租住人口数，外卖/闪送人数
                model = new Modelbuilding();
                model.name = "隐患整改数量";
                model.value = res.zgcount;
                model.unit = "个";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "电动自行车清理数量";
                model.value = res.ddzxcsl;
                model.unit = "辆";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "出租房间数量";
                model.value = res.czfjsl;
                model.unit = "间";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "租住人口数";
                model.value = res.zzrs;
                model.unit = "人";
                models.Add(model);

                model = new Modelbuilding();
                model.name = "外卖/闪送/代驾人数";
                model.value = res.czryrs;
                model.unit = "人";
                models.Add(model);


                return new RespRet<List<Modelbuilding>>(true, "Ok", models);
            }
            catch (Exception ex)
            {
                return null;
            }
        }



        /// <summary>
        /// 2.各区检查进度（第二行第一列，检查率排行）
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/cj_2gqjczd")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGenic), 200)]
        public RespRet<List<ModelGenic>> cj_gqjczd([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 	    SELECT  replace(xzq, '区','')  name,
 		 concat(round(((jccount / NULLIF(zcount, 0))*100), 2))  AS count 
          FROM jcqkgqview    ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();

                return new RespRet<List<ModelGenic>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 3.检查发现隐患（隐患发现数量、隐患整改数量，第二行第二）
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/cj_3jcfxyh")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGeniccj), 200)]
        public RespRet<List<ModelGeniccj>> cj_jcfxyh([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 	    SELECT  replace(xzq, '区','')  name,yhcount,zgcount FROM jcqkgqview   
		    ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGeniccj>(sql).ToList();

                return new RespRet<List<ModelGeniccj>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        /// 4.电动自行车检查情况（电动自行车总数、检查清理数量，第二行第三）
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/cj_4ddcjcqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGeniccj), 200)]
        public RespRet<List<ModelGeniccj>> cj_ddcjcqk([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 	  		
  SELECT   
                       replace(t1.xzq , '区','') AS name,
                        COALESCE(t1.bdfwjzrydddzxcsl, 0) AS bdfwjzrydddzxcsl,  
                        COALESCE(t2.qlddzxcsl, 0) AS qlddzxcsl
                    FROM  
                        (SELECT   
                             xzq,xzqdm,   
                             bdfwjzrydddzxcsl
                         FROM jcjbxxgqview) t1  
                    LEFT JOIN  
                        (SELECT   
                             xzq,xzqdm,  
                             COALESCE(qlddzxcsl, 0) AS qlddzxcsl
                         FROM zm_pc_gjzz_cj) t2 
                    ON t1.xzq = t2.xzq order by t1.xzqdm;
  
		    ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGeniccj>(sql).ToList();

                return new RespRet<List<ModelGeniccj>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }



        /// <summary>
        /// 5.各区检查隐患占比（第三行）
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/cj_5gqjcyhzb")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGeniccj), 200)]
        public RespRet<List<ModelGeniccj>> cj_gqjcyhzb([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 	 		
              SELECT REPLACE(max(xzq), '区', '') AS name,
                       ROUND(SUM(jccount) / SUM(SUM(jccount)) OVER () * 100, 2) AS gqyhzb,
                       CASE
                           WHEN SUM(zcount) <> 0 THEN CONCAT(ROUND((SUM(jccount) / SUM(zcount)) * 100, 2))
                           ELSE '0'
                       END AS count
                FROM jcqkgqview
                GROUP BY xzqdm


                 ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGeniccj>(sql).ToList();

                return new RespRet<List<ModelGeniccj>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        /// 6.隐患七项占比（第三行第二个）
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/cj_6yhqxzb")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGeniccj), 200)]
        public RespRet<List<ModelGeniccj>> cj_6yhqxzb([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 	  
                SELECT '私拉乱接电线' AS name, ROUND(SUM(slljdx) / NULLIF(SUM(slljdx + ygbjwfwhyx + use_stacked_items + mhqwbcwhyx + use_electric_bicycle + use_bottled_liquefied_gas + jyplmhxtwbcwhyx), 0) * 100, 2) AS count
                FROM jcyhgqview
                UNION ALL
                SELECT '烟感报警器未保持完好有效', ROUND(SUM(ygbjwfwhyx) / NULLIF(SUM(slljdx + ygbjwfwhyx + use_stacked_items + mhqwbcwhyx + use_electric_bicycle + use_bottled_liquefied_gas + jyplmhxtwbcwhyx), 0) * 100, 2)
                FROM jcyhgqview
                UNION ALL
                SELECT '影响人员疏散的堆放物品', ROUND(SUM(use_stacked_items) / NULLIF(SUM(slljdx + ygbjwfwhyx + use_stacked_items + mhqwbcwhyx + use_electric_bicycle + use_bottled_liquefied_gas + jyplmhxtwbcwhyx), 0) * 100, 2)
                FROM jcyhgqview
                UNION ALL
                SELECT '灭火器未保持完好有效', ROUND(SUM(mhqwbcwhyx) / NULLIF(SUM(slljdx + ygbjwfwhyx + use_stacked_items + mhqwbcwhyx + use_electric_bicycle + use_bottled_liquefied_gas + jyplmhxtwbcwhyx), 0) * 100, 2)
                FROM jcyhgqview
                UNION ALL
                SELECT '室内停放、充电电动车数量', ROUND(SUM(use_electric_bicycle) / NULLIF(SUM(slljdx + ygbjwfwhyx + use_stacked_items + mhqwbcwhyx + use_electric_bicycle + use_bottled_liquefied_gas + jyplmhxtwbcwhyx), 0) * 100, 2)
                FROM jcyhgqview
                UNION ALL
                SELECT '使用瓶装液化石油气数量', ROUND(SUM(use_bottled_liquefied_gas) / NULLIF(SUM(slljdx + ygbjwfwhyx + use_stacked_items + mhqwbcwhyx + use_electric_bicycle + use_bottled_liquefied_gas + jyplmhxtwbcwhyx), 0) * 100, 2)
                FROM jcyhgqview
                UNION ALL
                SELECT '简易喷淋灭火系统未保持完好有效', ROUND(SUM(jyplmhxtwbcwhyx) / NULLIF(SUM(slljdx + ygbjwfwhyx + use_stacked_items + mhqwbcwhyx + use_electric_bicycle + use_bottled_liquefied_gas + jyplmhxtwbcwhyx), 0) * 100, 2)
                FROM jcyhgqview;

                ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGeniccj>(sql).ToList();

                return new RespRet<List<ModelGeniccj>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        ///  7.城管委统计（外卖/闪送/代驾人员分布情况，第三行最后一个）
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/cj_7cgwtjwm")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGeniccj), 200)]
        public RespRet<List<ModelGeniccj>> HouseMngJbxxddccjjcl([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 	
												
  		 select replace(t1.xzq, '区','')  name,coalesce(t2.czryrs,0) czryrs from 
	    (select xzqdm,max(xzq)xzq from zm_building_ledger where  xzq not in ('北京市经济技术开发区','东城区','西城区') GROUP BY xzqdm )  t1 left join  
	    (select xzqdm,sum(czryrs) czryrs
    from zm_pc_base_cj   group by xzqdm order by xzqdm) t2 on t2.xzqdm=t1.xzqdm ORDER BY t1.xzqdm

		    ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGeniccj>(sql).ToList();

                return new RespRet<List<ModelGeniccj>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }




        /// 获取各区电动自行车数量
        [HttpGet("houses/checkjbxxddc")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGenic), 200)]
        public RespRet<List<ModelGenic>> HouseMngJbxxddc([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @" 	select ""replace""(t1.xzq, '区','')  name,coalesce(t2.ddzxcsl,0) count from 
																(select xzqdm,max(xzq)xzq from zm_building_ledger where  xzq not in ('北京市经济技术开发区','东城区','西城区') GROUP BY xzqdm )  t1 left join  
																(select xzqdm,sum(bdfwjzrydddzxcsl) ddzxcsl
                                from zm_pc_base   group by xzqdm order by xzqdm) t2 on t2.xzqdm=t1.xzqdm ORDER BY t1.xzqdm ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();

                return new RespRet<List<ModelGenic>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// 获取各区租住人口情况
        [HttpGet("houses/checkjbxxzzrk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGenic), 200)]
        public RespRet<List<ModelGenic>> HouseMngJbxxzzrk([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @"	select ""replace""(t1.xzq, '区','') name,coalesce(t2.zzrs,0) count from 
																(select xzqdm,max(xzq)xzq from zm_building_ledger where  xzq not in ('北京市经济技术开发区','东城区','西城区') GROUP BY xzqdm )  t1 left join  
																(select xzqdm,sum(zzrs) zzrs
                                from zm_pc_base   group by xzqdm order by xzqdm) t2 on t2.xzqdm=t1.xzqdm ORDER BY t1.xzqdm ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();

                return new RespRet<List<ModelGenic>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// 获取各区疏散通道数量
        [HttpGet("houses/checkjbxxsstd")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGenic), 200)]
        public RespRet<List<ModelGenic>> HouseMngJbxxsstd([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                string sql = @"	select ""replace""(t1.xzq, '区','') name,coalesce(t2.jzxyssltsl,0) count from 
																(select xzqdm,max(xzq)xzq from zm_building_ledger where  xzq not in ('北京市经济技术开发区','东城区','西城区') GROUP BY xzqdm )  t1 left join  
																(select xzqdm,sum(jzxyssltsl) jzxyssltsl
                                from zm_pc_base   group by xzqdm order by xzqdm) t2 on t2.xzqdm=t1.xzqdm ORDER BY t1.xzqdm ";
                var resmodel = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();

                return new RespRet<List<ModelGenic>>(true, "Ok", resmodel);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// 获取疏散通道数量达标  防烟逃生  悬挂警示 
        [HttpGet("houses/checkjbxxthree")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(ModelGenic), 200)]
        public RespRet<List<List<ModelGenic>>> HouseMngJbxxThree([FromQuery] PagePcztRequestInput pageRequest)
        {
            try
            {
                List<List<ModelGenic>> models = new List<List<ModelGenic>>();
                string sql = @"		select ""replace""(t1.xzq, '区','') name,coalesce(t2.tddbsl,0) count from 
																(select xzqdm,max(xzq)xzq from zm_building_ledger where  xzq not in ('北京市经济技术开发区','东城区','西城区') GROUP BY xzqdm )  t1 left join  
																(select xzqdm,sum(case when jzxyssltsl>=2  then 1 else 0 end ) tddbsl
                                from zm_pc_base   group by xzqdm order by xzqdm) t2 on t2.xzqdm=t1.xzqdm ORDER BY t1.xzqdm ";
                var resmodel1 = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();
                models.Add(resmodel1);

                sql = @"																select ""replace""(t1.xzq, '区','') name,coalesce(t2.fytsmzsl,0) count from 
																(select xzqdm,max(xzq)xzq from zm_building_ledger where  xzq not in ('北京市经济技术开发区','东城区','西城区') GROUP BY xzqdm )   t1 left join  
																(select xzqdm,sum(fytsmz) fytsmzsl
                                from zm_pc_base   group by xzqdm order by xzqdm) t2 on t2.xzqdm=t1.xzqdm ORDER BY t1.xzqdm ";
                var resmodel2 = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();
                models.Add(resmodel2);


                sql = @"																	
select ""replace""(t1.xzq, '区','') name,coalesce(t2.xggdjsbp,0) count from 
																(select xzqdm,max(xzq)xzq from zm_building_ledger where  xzq not in ('北京市经济技术开发区','东城区','西城区') GROUP BY xzqdm )   t1 left join  
																(select xzqdm,sum(xggdjsbp) xggdjsbp
                                from zm_pc_base   group by xzqdm order by xzqdm) t2 on t2.xzqdm=t1.xzqdm ORDER BY t1.xzqdm ";
                var resmodel3 = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();
                models.Add(resmodel3);


                return new RespRet<List<List<ModelGenic>>>(true, "Ok", models);
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        /// <summary>
        /// 获取其他经营液态 
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkqtjyyt")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingQtJjYt>>), 200)]
        public RespRet<List<BuildingQtJjYt>> HouseMngQtjyYt([FromQuery] PagePcztRequestInput pageRequest)
        {
            string sql = @"select  count(*)   count,aa  name from (select regexp_split_to_table(cjzwqtjyytmsg,',') aa
                       from (select REPLACE(cjzwqtjyytmsg  ,'|',',')  cjzwqtjyytmsg  from zm_pc_base  )  sd ) st
                         group by aa ";
            var list = _dbContext.Database.GetDbConnection().Query<BuildingQtJjYt>(sql).ToList();


            return new RespRet<List<BuildingQtJjYt>>(true, "Ok", list);
        }




        /// <summary>
        /// 获取各区电动车数量、 电动设施数量、消防车道数量  来源于村
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkgqjbxx")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildinggqJbxx>>), 200)]
        public RespRet<Page<BuildinggqJbxx>> HouseMnggqJbxx([FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildinggqJbxx>>(false, "PageIndex must >= 0");
            }
            string sql = @"select t1.xzqdm,t1.xzq,t1.zcount,coalesce(t2.ddcsl,0) ddcsl,coalesce(t2.ddsssl,0) ddsssl,coalesce(t2.xfctdsl,0)  xfctdsl from (select count(fwbh) zcount,xzqdm,xzq  from zm_buildings group by  xzqdm,xzq ) t1
                           left join 
                        (select  coalesce(sum(qlddzxcsl),0) ddcsl,xzqdm,coalesce(sum(qcxycdjk),0)  ddsssl,coalesce(sum(xfctdsl),0)  xfctdsl  from (
                           select *, row_number() over (partition by ttt.villagedm order by ttt.pcsj desc) as group_idx
                        from zm_pc_gjzz_cjlog  ttt) s
                        where s.group_idx = 1   group by xzqdm)  t2 on t1.xzqdm=t2.xzqdm     limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            var list = _dbContext.Database.GetDbConnection().Query<BuildinggqJbxx>(sql).ToList();
            int count = list.Count;

            var pageData = new Page<BuildinggqJbxx>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildinggqJbxx>>(true, "Ok", pageData);
        }


        /// <summary>
        /// 获取各区 租住人数数量、悬挂固定警示标牌、疏散楼梯数量、防烟逃生面罩、灭火器数量 来源于自查
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkgqjbxx2")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildinggqJbxx2>>), 200)]
        public RespRet<Page<BuildinggqJbxx2>> HouseMnggqJbxx2([FromQuery] PagePcztRequestInput pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<BuildinggqJbxx2>>(false, "PageIndex must >= 0");
            }


            string sql = @"select * from (select count(fwbh) zcount,xzqdm,xzq  from zm_buildings group by  xzqdm,xzq ) t1
                          left join 
                         (select coalesce(sum(zzrs),0) zzrksl,coalesce(sum(xggdjsbp),0)  xggdjsbp,coalesce(sum(jzxyssltsl),0) ssltsl,
                          coalesce(sum(fytsmz),0)  fytsmz,coalesce(sum(mhqsl),0),xzqdm
                      from (
                         select *, row_number() over (partition by ttt.fwbh order by ttt.pcsj desc) as group_idx
                         from zm_pc_baselog  ttt
                         ) s
                        where s.group_idx = 1 group by xzqdm ) t2   on t1.xzqdm=t2.xzqdm     limit " + pageRequest.Limit + " offset " + pageRequest.Limit * pageRequest.PageIndex;
            var list = _dbContext.Database.GetDbConnection().Query<BuildinggqJbxx2>(sql).ToList();
            int count = list.Count;

            var pageData = new Page<BuildinggqJbxx2>(list
                , pageRequest.PageIndex + 1, pageRequest.Limit, count);
            return new RespRet<Page<BuildinggqJbxx2>>(true, "Ok", pageData);
        }


        #endregion

        #region 隐患信息 页
        /// <summary>
        /// 隐患数量统计  各个隐患项名称、id和数量
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkyhtj")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<ModelGenic>>), 200)]
        public RespRet<List<ModelGenic>> HouseMngYhtj([FromQuery] PagePcztRequestInput pageRequest)
        {
            string sql = @"select   count(*)   count,check_name name   from(select check_name,check_id from zm_pc_yhlog_dx  
                     union all 
                     select check_name,check_id from zm_pc_yhlog_dx_cj
                     union all 
                     select check_name,check_id from zm_pc_yhlog_dx_xz)  t1 group by check_name,check_id  limit ";
            var res = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();

            return new RespRet<List<ModelGenic>>(true, "Ok", res);
        }

        /// <summary>
        /// 自查  村级 乡镇查询隐患数量情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkcjxzyh")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<ModelGenic>>), 200)]
        public RespRet<List<ModelGenic>> HouseMngCjXzyh([FromQuery] PagePcztRequestInput pageRequest)
        {
            string sql = @" select count(*) count,'自查隐患' name from zm_pc_yhlog_dx
												union ALL
												select count(*) count,'村级隐患' name from zm_pc_yhlog_dx_cj
												union ALL
												select count(*) count,'乡镇隐患' name from zm_pc_yhlog_dx_xz";
            var list = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();
            int count = list.Count;

            return new RespRet<List<ModelGenic>>(true, "Ok", list);
        }

        /// <summary>
        /// 房屋总数 隐患总数 整改隐患 剩余隐患  
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/checkJbxxyh")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<List<ModelGenic>>), 200)]
        public RespRet<List<ModelGenic>> HouseMngJbxxYh([FromQuery] PagePcztRequestInput pageRequest)
        {
            string sql = @" select count(*) count,'房屋总数' name   from zm_buildings
				union ALL   select count(*) count,'隐患总数' name   from zm_pc_yhlog_dx
				union ALL   select count(*) count,'整改总数' name   from zm_pc_yhlog_dx where zg_value='1'
				union ALL   select count(*) count,'剩余隐患' name   from zm_pc_yhlog_dx where zg_value='0'";
            var list = _dbContext.Database.GetDbConnection().Query<ModelGenic>(sql).ToList();
            int count = list.Count;

            return new RespRet<List<ModelGenic>>(true, "Ok", list);
        }
        #endregion




        /// <summary>
        /// 大屏展示 基本信息
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/dpzsjbxx")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<BuildingCjxzYh>>), 200)]
        public RespRet<object> Dpzsjbxx()
        {

            var userNumber = this.CurrentUser();
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<object>(false, "user not logined");
            }
            string sql = @"select * from (select count(1) zs,count(b.fwbh) zcfwsl from zm_buildings a left join zm_pc_base b on a.fwbh=b.fwbh) a,
(select count(1)fxyhs ,count( case when zg_value=1 then 1 end) zgyhs from zm_pc_yhlog_dx)b  ";
            var list = _dbContext.Database.GetDbConnection().Query<object>(sql).ToList();
            int count = list.Count;

            return new RespRet<object>(true, "Ok", list);
        }






        /// <summary>
        /// 自定义sql
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/excute")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> excute([FromQuery] string id)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return new RespRet<object>(false, "id不能为空");
                }
                var sql = _dbContext.ZmSql.FirstOrDefault(x => x.Id == id);
                if (sql == null)
                {
                    return new RespRet<object>(false, "未找到可执行语句，请传递正确id");
                }
                // var data= _dbContext.Database.GetDbConnection().Query<dynamic>(sql.Value, null).FirstOrDefault();
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql.Value, null);
                //var a = ConvertObjectFieldsToList(data);
                return new RespRet<object>(true, "Ok", data);
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/excute", res);
                res.Msg = "系统异常";
                return res;
            }
        }




        /// <summary>
        /// 自定义sql
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/excuteobject")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> excuteobject([FromQuery] string id)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return new RespRet<object>(false, "id不能为空");
                }
                var sql = _dbContext.ZmSql.FirstOrDefault(x => x.Id == id);
                if (sql == null)
                {
                    return new RespRet<object>(false, "未找到可执行语句，请传递正确id");
                }
                var data = _dbContext.Database.GetDbConnection().Query<dynamic>(sql.Value, null).FirstOrDefault();
                //var data = _dbContext.Database.GetDbConnection().Query<object>(sql.Value, null);
                //var a = ConvertObjectFieldsToList(data);
                return new RespRet<object>(true, "Ok", data);
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/excute", res);
                res.Msg = "系统异常";
                return res;
            }
        }

        /// <summary>
        /// 自定义sql
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/Jbxx")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> Jbxx([FromQuery] string code)
        {
            var usernNumber = this.CurrentUser();
            try
            {

                if (string.IsNullOrWhiteSpace(code))
                {
                    code = "110000";
                }
                var len = code.Replace("000", "").Length;
                string sql = @" select case when sum(zcount) is null then 0 else sum(zcount) end 经营性自建房数量, 
case when sum(zccount) is null then 0 else sum(zccount) end 自查房屋数量,case when  sum(yhcount) is null then 0 else sum(yhcount) end  自查隐患数量,
case when sum(zgcount) is null then 0 else sum(zgcount) end 整改隐患数量   from zcqkgqview
 ";
                if (len == 6)
                {
                    sql = @" select case when sum(zcount) is null then 0 else sum(zcount) end 经营性自建房数量, 
case when sum(zccount) is null then 0 else sum(zccount) end 自查房屋数量,case when  sum(yhcount) is null then 0 else sum(yhcount) end  自查隐患数量,
case when sum(zgcount) is null then 0 else sum(zgcount) end 整改隐患数量   from zcqkgqview where xzqdm like @code ";
                }
                if (len == 9)
                {
                    sql = @"  select case when sum(zcount) is null then 0 else sum(zcount) end 经营性自建房数量, 
case when sum(zccount) is null then 0 else sum(zccount) end 自查房屋数量,case when  sum(yhcount) is null then 0 else sum(yhcount) end  自查隐患数量,
case when sum(zgcount) is null then 0 else sum(zgcount) end 整改隐患数量   from zcqkxzview where towndm like @code ";
                }
                if (len == 12)
                {
                    sql = @" select case when sum(zcount) is null then 0 else sum(zcount) end 经营性自建房数量, 
case when sum(zccount) is null then 0 else sum(zccount) end 自查房屋数量,case when  sum(yhcount) is null then 0 else sum(yhcount) end  自查隐患数量,
case when sum(zgcount) is null then 0 else sum(zgcount) end 整改隐患数量   from zcqkcjview where villagedm like @code ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<dynamic>(sql, new { @code = "%" + code + "%" }).FirstOrDefault();
                List<object> list = new List<object>();
                if (data is object)
                {
                    var expando = (IDictionary<string, object>)data;
                    int i = 0;
                    foreach (var property in expando)
                    {
                        string propertyName = property.Key;
                        object propertyValue = property.Value;
                        list.Add(new { name = propertyName, value = propertyValue, unit = stringList[i] });
                        i++;
                    }
                }
                ////var data = _dbContext.Database.GetDbConnection().Query<object>(sql.Value, null).FirstOrDefault();
                return new RespRet<object>(true, "Ok", list);
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                WriteSystemLog(usernNumber, "houses/excute", res);
                res.Msg = "系统异常";
                return res;
            }
        }



        static Dictionary<string, object> ConvertDynamicObjectToDictionary(dynamic obj)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            if (obj != null)
            {
                var properties = obj as IDictionary<string, object>;
                foreach (var kvp in properties)
                {
                    dictionary.Add(kvp.Key, kvp.Value);
                }
            }
            return dictionary;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/excutetb")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> Excutetb(string id, string param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(id))
                {
                    return new RespRet<object>(false, "id不能为空");
                }
                if (string.IsNullOrWhiteSpace(id))
                {
                    return new RespRet<object>(false, "id不能为空");
                }
                var sql = _dbContext.ZmSql.FirstOrDefault(x => x.Id == id);
                if (sql == null)
                {
                    return new RespRet<object>(false, "未找到可执行语句，请传递正确id");
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql.Value, null).FirstOrDefault();

                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (data != null)
                {
                    var properties = data as IDictionary<string, object>;
                    foreach (var kvp in properties)
                    {
                        var stringlist = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        var list = new List<string>();
                        foreach (var item in stringlist)
                        {
                            list.Add(item);
                        }
                        dictionary.Add(kvp.Key, list);
                    }
                    var r = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/excute", r);
                    return r;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/excute", res);
                return res;
            }

            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), new { id = id, param = param });
                WriteSystemLog(usernNumber, "houses/excute", res);
                res.Msg = "系统异常";
                return res;
            }
        }

        /// <summary>
        /// 人员疏散通道建设情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/rysstdjsqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> Rysstdjsqk(string code)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(code))
                {
                    code = "110000";
                }
                string sql = @$"  SELECT 
    CONCAT('[', STRING_AGG(xzq, ', ' ORDER BY xzqdm ASC), ']') AS x,
    CONCAT('[', STRING_AGG(CAST(zzzdfa AS VARCHAR), ', ' ORDER BY xzqdm ASC), ']') AS zzzdfa,
    CONCAT('[', STRING_AGG(CAST(zzsggz AS VARCHAR), ', ' ORDER BY xzqdm ASC), ']') AS zzsggz,
    CONCAT('[', STRING_AGG(CAST(sstdywc AS VARCHAR), ', ' ORDER BY xzqdm ASC), ']') AS ywc from  jbxxgqview ;
";
                code = code.Replace("000", "");
                var lea = code.Replace("000", "").Length;
                if (lea == 6)
                {
                    sql = @$"  SELECT 
    CONCAT('[', STRING_AGG(town, ', ' ORDER BY towndm ASC), ']') AS x,
    CONCAT('[', STRING_AGG(CAST(zzzdfa AS VARCHAR), ', ' ORDER BY towndm ASC), ']') AS zzzdfa,
    CONCAT('[', STRING_AGG(CAST(zzsggz AS VARCHAR), ', ' ORDER BY towndm ASC), ']') AS zzsggz,
    CONCAT('[', STRING_AGG(CAST(sstdywc AS VARCHAR), ', ' ORDER BY towndm ASC), ']') AS ywc from  jbxxxzview where towndm like @code ";
                }
                if (lea == 9)
                {
                    sql = @$"  SELECT 
    CONCAT('[', STRING_AGG(village, ', ' ORDER BY villagedm ASC), ']') AS x,
    CONCAT('[', STRING_AGG(CAST(zzzdfa AS VARCHAR), ', ' ORDER BY villagedm ASC), ']') AS zzzdfa,
    CONCAT('[', STRING_AGG(CAST(zzsggz AS VARCHAR), ', ' ORDER BY villagedm ASC), ']') AS zzsggz,
    CONCAT('[', STRING_AGG(CAST(sstdywc AS VARCHAR), ', ' ORDER BY villagedm ASC), ']') AS ywc from  jbxxcjview where villagedm like @code ";
                }
                if (lea == 12)
                {
                    sql = @$" SELECT 
    CONCAT('[', STRING_AGG(village, ', ' ORDER BY villagedm ASC), ']') AS x,
    CONCAT('[', STRING_AGG(CAST(zzzdfa AS VARCHAR), ', ' ORDER BY villagedm ASC), ']') AS zzzdfa,
    CONCAT('[', STRING_AGG(CAST(zzsggz AS VARCHAR), ', ' ORDER BY villagedm ASC), ']') AS zzsggz,
    CONCAT('[', STRING_AGG(CAST(sstdywc AS VARCHAR), ', ' ORDER BY villagedm ASC), ']') AS ywc from  jbxxcjview where villagedm like @code ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + code + "%" }).FirstOrDefault();
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (data != null)
                {
                    var properties = data as IDictionary<string, object>;
                    foreach (var kvp in properties)
                    {
                        var stringlist = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        var list = new List<string>();
                        foreach (var item in stringlist)
                        {
                            list.Add(item);
                        }
                        dictionary.Add(kvp.Key, list);
                    }
                    var r = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/rysstdjsqk", r);
                    return r;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/rysstdjsqk", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), code);
                WriteSystemLog(usernNumber, "houses/rysstdjsqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }





        /// <summary>
        /// 消防隐患处理情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/xfyhclqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> Xfyhclqk(string code)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(code))
                {
                    code = "110000";
                }
                string sql = @$" select 
   CONCAT('[', STRING_AGG(xzq, ', ' ORDER BY xzqdm ASC), ']') AS x,
	 CONCAT('[', STRING_AGG(yhcount::text, ', ' ORDER BY xzqdm ASC), ']') AS yhcount,
   CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ORDER BY xzqdm ASC), ']') AS zgcount from
zcqkgqview
";

                code = code.Replace("000", "");
                var lea = code.Replace("000", "").Length;
                if (lea == 6)
                {
                    sql = @$" select 
   CONCAT('[', STRING_AGG(xzq, ', ' ORDER BY xzqdm ASC), ']') AS x,
	 CONCAT('[', STRING_AGG(yhcount::text, ', ' ORDER BY xzqdm ASC), ']') AS yhcount,
   CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ORDER BY xzqdm ASC), ']') AS zgcount from
zcqkxzview where towndm like @code
";
                }
                if (lea == 9)
                {
                    sql = @$" select 
   CONCAT('[', STRING_AGG(xzq, ', ' ORDER BY xzqdm ASC), ']') AS x,
	 CONCAT('[', STRING_AGG(yhcount::text, ', ' ORDER BY xzqdm ASC), ']') AS yhcount,
   CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ORDER BY xzqdm ASC), ']') AS zgcount from
zcqkcjview where villagedm like @code
";
                }
                if (lea == 12)
                {
                    sql = @$" select 
   CONCAT('[', STRING_AGG(xzq, ', ' ORDER BY xzqdm ASC), ']') AS x,
	 CONCAT('[', STRING_AGG(yhcount::text, ', ' ORDER BY xzqdm ASC), ']') AS yhcount,
   CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ORDER BY xzqdm ASC), ']') AS zgcount from
zcqkcjview where villagedm like @code ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + code + "%" }).FirstOrDefault();
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (data != null)
                {
                    var properties = data as IDictionary<string, object>;
                    foreach (var kvp in properties)
                    {
                        var stringlist = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        var list = new List<string>();
                        foreach (var item in stringlist)
                        {
                            list.Add(item);
                        }
                        dictionary.Add(kvp.Key, list);
                    }
                    var r = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/xfyhclqk", r);
                    return r;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/xfyhclqk", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), code);
                WriteSystemLog(usernNumber, "houses/xfyhclqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }




        /// <summary>
        /// 清理室内电动自行车情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/qlsnddzxcqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> Qlsnddzxcqk(string code)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(code))
                {
                    code = "110000";
                }
                string sql = @$" 
  select CONCAT('[', STRING_AGG(region_name, ', '), ']') AS x,CONCAT('[', STRING_AGG(CAST(zs AS VARCHAR), ', ' ), ']') AS zs,CONCAT('[', STRING_AGG(CAST(qlddcsl AS VARCHAR), ', ' ), ']') AS qlddcsl from ( select  region_name,case when zs is null then 0 else zs end zs,case when qlddcsl is null then 0 else qlddcsl end qlddcsl   from   (select bdfwjzrydddzxcsl zs,xzqdm region_code from jbxxgqview)a
join 
(select  sum(zxqlddcsl) qlddcsl,c.region_code,max(c.region_name) region_name from zm_pc_yhlog a left join zm_buildings b on a.fwbh=b.fwbh RIGHT JOIN (select xzqdm region_code,max(xzq) region_name from  zm_building_ledger where  xzq not in ('东城区','西城区')GROUP BY xzqdm ) c on b.xzqdm=c.region_code  GROUP BY c.region_code ORDER BY c.region_code) b on a.region_code=b.region_code) a

";

                code = code.Replace("000", "");
                var lea = code.Replace("000", "").Length;
                if (lea == 6)
                {
                    sql = @$"  select CONCAT('[', STRING_AGG(region_name, ', '), ']') AS x,CONCAT('[', STRING_AGG(CAST(zs AS VARCHAR), ', ' ), ']') AS zs,CONCAT('[', STRING_AGG(CAST(qlddcsl AS VARCHAR), ', ' ), ']') AS qlddcsl from ( select  region_name,case when zs is null then 0 else zs end zs,case when qlddcsl is null then 0 else qlddcsl end qlddcsl   from   (select bdfwjzrydddzxcsl zs,towndm region_code from jbxxxzview)a
join 
(select  sum(zxqlddcsl) qlddcsl,c.region_code,max(c.region_name) region_name from zm_pc_yhlog a left join zm_buildings b on a.fwbh=b.fwbh RIGHT JOIN (select towndm region_code,max(town) region_name from  zm_building_ledger where towndm like @code  GROUP BY towndm ) c on b.towndm=c.region_code  GROUP BY c.region_code ORDER BY c.region_code) b on a.region_code=b.region_code) a";
                }
                if (lea == 9)
                {
                    sql = @$"  select CONCAT('[', STRING_AGG(region_name, ', '), ']') AS x,CONCAT('[', STRING_AGG(CAST(zs AS VARCHAR), ', ' ), ']') AS zs,CONCAT('[', STRING_AGG(CAST(qlddcsl AS VARCHAR), ', ' ), ']') AS qlddcsl from ( select  region_name,case when zs is null then 0 else zs end zs,case when qlddcsl is null then 0 else qlddcsl end qlddcsl   from   (select bdfwjzrydddzxcsl zs,villagedm region_code from jbxxcjview)a
join 
(select  sum(zxqlddcsl) qlddcsl,c.villagedm,max(c.village) region_name from zm_pc_yhlog a left join zm_buildings b on a.fwbh=b.fwbh RIGHT JOIN  zm_building_ledger c  on b.villagedm=c.villagedm  where c.villagedm like @code GROUP BY c.villagedm ORDER BY c.villagedm) b on a.villagedm=b.villagedm) a";
                }
                if (lea == 12)
                {
                    sql = @$"   select CONCAT('[', STRING_AGG(region_name, ', '), ']') AS x,CONCAT('[', STRING_AGG(CAST(zs AS VARCHAR), ', ' ), ']') AS zs,CONCAT('[', STRING_AGG(CAST(qlddcsl AS VARCHAR), ', ' ), ']') AS qlddcsl from ( select  region_name,case when zs is null then 0 else zs end zs,case when qlddcsl is null then 0 else qlddcsl end qlddcsl   from   (select bdfwjzrydddzxcsl zs,villagedm region_code from jbxxcjview)a
join 
(select  sum(zxqlddcsl) qlddcsl,c.villagedm,max(c.village) region_name from zm_pc_yhlog a left join zm_buildings b on a.fwbh=b.fwbh RIGHT JOIN  zm_building_ledger c  on b.villagedm=c.villagedm  where c.villagedm like @code GROUP BY c.villagedm ORDER BY c.villagedm) b on a.villagedm=b.villagedm) a ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + code + "%" }).FirstOrDefault();
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (data != null)
                {
                    var properties = data as IDictionary<string, object>;
                    foreach (var kvp in properties)
                    {
                        var stringlist = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        var list = new List<string>();
                        foreach (var item in stringlist)
                        {
                            list.Add(item);
                        }
                        dictionary.Add(kvp.Key, list);
                    }
                    var r = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/qlsnddzxcqk", r);
                    return r;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/qlsnddzxcqk", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), code);
                WriteSystemLog(usernNumber, "houses/qlsnddzxcqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }



        /// <summary>
        /// 自防自救力量建设
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/zfzjlljs")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> Zfzjlljs(string code)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(code))
                {
                    code = "110000";
                }
                string sql = @$" 
 select a.region_name,zzxfd,wxxfz,case when sum is null then 0 else sum end rkzs
from (select max(region_name) region_name,region_code,count(case when sfjszzxfdhxxxfz=1 then 1 end) zzxfd,count(case when sfjswxxfz=1 then 1 end) wxxfz from zm_pc_gjzz_cj a RIGHT JOIN (select xzqdm region_code,max(xzq) region_name from  zm_building_ledger where  xzq not in ('东城区','西城区') group by xzqdm) b on a.xzqdm=b.region_code  GROUP BY region_code) a
join
(select  max(region_name) region_name,sum(jzrks),region_code  from zm_pc_base a RIGHT JOIN (select xzqdm region_code,max(xzq) region_name from  zm_building_ledger where  xzq not in ('东城区','西城区') group by xzqdm) b on a.xzqdm=b.region_code  GROUP BY region_code)b on a.region_code=b.region_code ORDER BY  a.region_code
";

                code = code.Replace("000", "");
                var lea = code.Replace("000", "").Length;
                if (lea == 6)
                {
                    sql = @$"  select a.region_name,zzxfd,wxxfz,case when sum is null then 0 else sum end rkzs
from (select max(region_name) region_name,region_code,count(case when sfjszzxfdhxxxfz=1 then 1 end) zzxfd,count(case when sfjswxxfz=1 then 1 end) wxxfz from zm_pc_gjzz_cj a RIGHT JOIN (select towndm region_code,max(town) region_name from  zm_building_ledger where towndm like @code  group by towndm) b on a.xzqdm=b.region_code  GROUP BY region_code) a
join
(select  max(region_name) region_name,sum(jzrks),region_code  from zm_pc_base a RIGHT JOIN (select towndm region_code,max(town) region_name from  zm_building_ledger where towndm like @code  group by towndm) b on a.xzqdm=b.region_code   GROUP BY region_code )b on a.region_code=b.region_code ORDER BY  a.region_code 
 ";
                }
                if (lea == 9)
                {
                    sql = @$"  select a.region_name,zzxfd,wxxfz,case when sum is null then 0 else sum end rkzs
from (select max(region_name) region_name,region_code,count(case when sfjszzxfdhxxxfz=1 then 1 end) zzxfd,count(case when sfjswxxfz=1 then 1 end) wxxfz from zm_pc_gjzz_cj a RIGHT JOIN (select villagedm region_code,max(village) region_name from  zm_building_ledger where villagedm like @code  group by villagedm) b on a.xzqdm=b.region_code  GROUP BY region_code) a
join
(select  max(region_name) region_name,sum(jzrks),region_code  from zm_pc_base a RIGHT JOIN (select villagedm region_code,max(village) region_name from  zm_building_ledger where villagedm like @code  group by villagedm) b on a.xzqdm=b.region_code   GROUP BY region_code )b on a.region_code=b.region_code ORDER BY  a.region_code 
  ";
                }
                if (lea == 12)
                {
                    sql = @$"  select a.region_name,zzxfd,wxxfz,case when sum is null then 0 else sum end rkzs
from (select max(region_name) region_name,region_code,count(case when sfjszzxfdhxxxfz=1 then 1 end) zzxfd,count(case when sfjswxxfz=1 then 1 end) wxxfz from zm_pc_gjzz_cj a RIGHT JOIN (select villagedm region_code,max(village) region_name from  zm_building_ledger where villagedm like @code  group by villagedm) b on a.xzqdm=b.region_code  GROUP BY region_code) a
join
(select  max(region_name) region_name,sum(jzrks),region_code  from zm_pc_base a RIGHT JOIN (select villagedm region_code,max(village) region_name from  zm_building_ledger where villagedm like @code  group by villagedm) b on a.xzqdm=b.region_code   GROUP BY region_code )b on a.region_code=b.region_code ORDER BY  a.region_code 
  ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + code + "%" });
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/zfzjlljs", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), code);
                WriteSystemLog(usernNumber, "houses/zfzjlljs", res);
                res.Msg = "系统异常";
                return res;
            }
        }






        /// <summary>
        /// 宣传警示开展情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        //        [HttpPost("houses/xcjskzqk")]
        //        [Produces("application/json")]
        //        [ProducesResponseType(typeof(RespRet<object>), 200)]
        //        public RespRet<object> Xcjskzqk([FromBody] DateQuery param)
        //        {
        //            var usernNumber = this.CurrentUser();
        //            try
        //            {
        //                if (param == null)
        //                {
        //                    return new RespRet<object>(false, "参数不能为空");
        //                }
        //                if (string.IsNullOrWhiteSpace(param.code))
        //                {
        //                    param.code = "110000";
        //                }
        //                param.code = param.code.Replace("000", "");
        //                string sql = @$" 
        //select xzq,xzqdm ,jzfjs jzfjs, xggdjsbp azgdjsbpsl,case when jzfjs=0 then 0.00||'%' else(case when  round(xggdjsbp*1.00*100/jzfjs,2) is null then 0.00||'%' when round(xggdjsbp*1.00*100/jzfjs,2)>100 then 100.00||'%' else round(xggdjsbp*1.00*100/jzfjs,2)||'%' end)end  wcl from jbxxgqview
        //";
        //                var lea = param.code.Replace("000", "").Length;
        //                if (lea == 6)
        //                {
        //                    sql = @$" select towndm,town,xzq,xzqdm ,jzfjs jzfjs, xggdjsbp azgdjsbpsl,case when jzfjs=0 then 0.00||'%' else(case when  round(xggdjsbp*1.00*100/jzfjs,2) is null then 0.00||'%' when round(xggdjsbp*1.00*100/jzfjs,2)>100 then 100.00||'%' else round(xggdjsbp*1.00*100/jzfjs,2)||'%' end)end  wcl from jbxxxzview
        //  where towndm like @code ";
        //                }
        //                if (lea == 9)
        //                {
        //                    sql = @$" select towndm,town,xzq,xzqdm,villagedm,village ,jzfjs jzfjs, xggdjsbp azgdjsbpsl,case when jzfjs=0 then 0.00||'%' else(case when  round(xggdjsbp*1.00*100/jzfjs,2) is null then 0.00||'%' when round(xggdjsbp*1.00*100/jzfjs,2)>100 then 100.00||'%' else round(xggdjsbp*1.00*100/jzfjs,2)||'%' end)end  wcl from jbxxcjview where villagedm like @code ";
        //                }
        //                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + param.code + "%" });
        //                Dictionary<string, object> dictionary = new Dictionary<string, object>();
        //                var res = new RespRet<object>(true, "Ok", data);
        //                WriteSystemLog(usernNumber, "houses/xcjskzqk", res);
        //                return res;
        //            }
        //            catch (Exception ex)
        //            {
        //                var res = new RespRet<object>(false, ex.ToString(), param.code);
        //                WriteSystemLog(usernNumber, "houses/xcjskzqk", res);
        //                res.Msg = "系统异常";
        //                return res;
        //            }
        //        }




        /// <summary>
        /// 宣传警示开展情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/Xcjskzqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> Xcjskzqk([FromBody] DateQuery param)
        {

            try
            {

                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                string time = DateTime.Today
.AddHours(23)
.AddMinutes(59)
.AddSeconds(59)
.ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                string sql = @$" select name,code,value||'%' value,value||'%' azl,xggdjsbpds,zcount,name xzq,code xzqdm from  gdjsbtbar_gq_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@tablename)
  "; param.code = param.code.Replace("000", "");
                var lea = param.code.Substring(param.code.Length - 3) == "000" ? param.code.Length - 3 : param.code.Length;

                if (lea == 6)
                {
                    sql = @$" select name,code,value||'%' value,value||'%' azl,xggdjsbpds,zcount,name town,code towndm from  gdjsbtbar_xz_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@code,@tablename) ";
                }
                if (lea == 12 || lea == 9)
                {
                    sql = @$" select village,code,value||'%' value,value||'%' azl,xggdjsbpds,zcount,village,code villagedm,xzqdm,xzq,town,towndm from  gdjsbtbar_cj_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@code,@tablename) ";
                }
                //if (lea == 12)
                //{
                //    sql = @$" select xggdjsbpds,zcount,towndm,town,xzq,xzqdm,villagedm,village,case when value >100 then 100.00 when value is null then 0.00 else value end value  from (  select xggdjsbpds,zcount, round(xggdjsbpds*1.00*100/zcount,2) value ,towndm,town,xzq,xzqdm,villagedm,village from  jbxxcjview where villagedm like @code  ORDER BY value desc) a ";
                //}
                var msg = _dbContext.Database.GetDbConnection().Query<object>(sql, new {@time=time,@tablename=table_name, @code = "%" + param.code + "%" }).ToList();
                var res = new RespRet<object>(true, "Ok", msg);
                //WriteSystemLog(usernNumber, "houses/Xcjskzqk", res);
                return new RespRet<object>(true, "Ok", msg);

            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), ex.ToString());
                WriteSystemLog(null, "houses/xcjskzqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 宣传警示开展情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/Xcjskzqkmsg")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> Xcjskzqkmsg([FromBody] DateQuery param)
        {
            try
            {
                string time = DateTime.Today
.AddHours(23)
.AddMinutes(59)
.AddSeconds(59)
.ToString("yyyy-MM-dd HH:mm:ss");
                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                string sql = @$" select xggdjsbpds,azl||'%' value from  gdjsbtbar_gq_total_text('','','2024-01-01',@time::timestamp,'zm_pc_base',@tablename)  ";

                var msg = _dbContext.Database.GetDbConnection().Query<object>(sql, new {@time=time, @code = "%" + param.code + "%" ,@tablename=table_name}).ToList();
                var res = new RespRet<object>(true, "Ok", msg);
                //WriteSystemLog(usernNumber, "houses/Xcjskzqkmsg", res);
                return new RespRet<object>(true, "Ok", msg);
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), ex.ToString());
                WriteSystemLog(null, "houses/Xcjskzqkmsg", res);
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 今日自查情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/zcqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> GetThisWork(string param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(param))
                {
                    param = "110000";
                }
                string sql = @$" select 
CONCAT('[', STRING_AGG(CAST(zczs AS VARCHAR), ', ' ), ']') AS zczs,
 CONCAT('[', STRING_AGG(CAST(yhcount AS VARCHAR), ', ' ), ']') AS yhcount,
 CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ), ']') AS zgcount from
(select *,zccount zczs From tzcqkgqview ORDER BY xzqdm)a
";
                var lea = param.Replace("000", "").Length;
                if (lea == 3)
                {
                    sql = @$" select 
CONCAT('[', STRING_AGG(CAST(zczs AS VARCHAR), ', ' ), ']') AS zczs,
 CONCAT('[', STRING_AGG(CAST(yhcount AS VARCHAR), ', ' ), ']') AS yhcount,
 CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ), ']') AS zgcount from
(select  sum(zccount) zczs,sum(yhcount) yhcount,sum(zgcount) zgcount  from tzcqkgqview) a ";
                }
                if (lea == 6)
                {
                    sql = @$" select 
CONCAT('[', STRING_AGG(CAST(zczs AS VARCHAR), ', ' ), ']') AS zczs,
 CONCAT('[', STRING_AGG(CAST(yhcount AS VARCHAR), ', ' ), ']') AS yhcount,
 CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ), ']') AS zgcount from
(select  sum(zccount) zczs,sum(yhcount) yhcount,sum(zgcount) zgcount  from tzcqkgqview where xzqdm like @code) a ";
                }


                if (lea == 9)
                {
                    sql = @$"select 
CONCAT('[', STRING_AGG(CAST(zczs AS VARCHAR), ', ' ), ']') AS zczs,
 CONCAT('[', STRING_AGG(CAST(yhcount AS VARCHAR), ', ' ), ']') AS yhcount,
 CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ), ']') AS zgcount from
(select  (select count(1) zczs from zm_pc_yhlog a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.towndm like @code )  ,
(select count(1) yhcount from zm_pc_yhlog_dx_cj a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.towndm like @code),
(select count(1) zgcount  from zm_pc_yhlog_dxzgson_cj a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.towndm like @code))a
";
                }
                if (lea == 12)
                {
                    sql = @$" select 
CONCAT('[', STRING_AGG(CAST(zczs AS VARCHAR), ', ' ), ']') AS zczs,
 CONCAT('[', STRING_AGG(CAST(yhcount AS VARCHAR), ', ' ), ']') AS yhcount,
 CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ), ']') AS zgcount from
(select  (select count(1) zczs from zm_pc_yhlog a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.villagedm like @code )  ,
(select count(1) yhcount from zm_pc_yhlog_dx_cj a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.villagedm like @code),
(select count(1) zgcount  from zm_pc_yhlog_dxzgson_cj a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.villagedm like @code))a    ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + param + "%" }).FirstOrDefault();
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                if (data != null)
                {
                    var properties = data as IDictionary<string, object>;
                    foreach (var kvp in properties)
                    {
                        var stringlist = kvp.Value.ToString().Trim('[', ']').Split(", ");
                        var list = new List<string>();
                        foreach (var item in stringlist)
                        {
                            list.Add(item);
                        }
                        dictionary.Add(kvp.Key, list);
                    }
                    var r = new RespRet<object>(true, "Ok", dictionary);
                    //WriteSystemLog(usernNumber, "houses/zcqk", r);
                    return r;
                }
                var res = new RespRet<object>(true, "Ok", data);
                //WriteSystemLog(usernNumber, "houses/zcqk", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), new { param = param });
                WriteSystemLog(usernNumber, "houses/zcqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }



        /// <summary>
        /// 今日自查情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpGet("houses/zcqktable")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> Zcqktable(string param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (string.IsNullOrWhiteSpace(param))
                {
                    param = "110000";
                }
                string sql = @$" ";
                string sqltitle = @$" ";
                string countsql = @$"";
                var lea = param.Replace("000", "").Length;
                if (lea == 3)
                {
                    countsql = @$" select   '合计' xzq ,sum(t)t,sum(t1)t1,sum(t2)t2,sum(t3)t3,sum(t4)t4,sum(t5)t5,sum(t6)t6,sum(b.fwds)fwds,1 index  From ( select  max(b.xzq) xzq,b.xzqdm, count (case when date(create_on)=date(now()) then 1 end)  t,
count (case when date(create_on)=date(now()) - INTERVAL '1 day' then 1 end) t1,
count (case when date(create_on)=date(now()) - INTERVAL '2 day' then 1 end) t2,
count (case when date(create_on)=date(now()) - INTERVAL '3 day' then 1 end) t3,
count (case when date(create_on)=date(now()) - INTERVAL '4 day' then 1 end) t4,
count (case when date(create_on)=date(now()) - INTERVAL '5 day' then 1 end) t5,
count (case when date(create_on)=date(now()) - INTERVAL '6 day' then 1 end) t6
from zm_pc_yh a RIGHT  join zm_building_ledger b on a.villagedm=b.villagedm  GROUP BY b.xzqdm) a JOIN (select xzqdm,case when sum(fwds::int) is null then 0 else sum(fwds::int) end  fwds from zm_building_ledger GROUP BY xzqdm) b
on a.xzqdm=b.xzqdm  ";
                    sql = @$" select a.*,b.fwds,1 index  From ( select  max(b.xzq) xzq,b.xzqdm, count (case when date(create_on)=date(now()) then 1 end)  t,
count (case when date(create_on)=date(now()) - INTERVAL '1 day' then 1 end) t1,
count (case when date(create_on)=date(now()) - INTERVAL '2 day' then 1 end) t2,
count (case when date(create_on)=date(now()) - INTERVAL '3 day' then 1 end) t3,
count (case when date(create_on)=date(now()) - INTERVAL '4 day' then 1 end) t4,
count (case when date(create_on)=date(now()) - INTERVAL '5 day' then 1 end) t5,
count (case when date(create_on)=date(now()) - INTERVAL '6 day' then 1 end) t6
from zm_pc_yh a RIGHT  join zm_building_ledger b on a.villagedm=b.villagedm  GROUP BY b.xzqdm) a JOIN (select xzqdm,case when sum(fwds::int) is null then 0 else sum(fwds::int) end  fwds from zm_building_ledger GROUP BY xzqdm) b
on a.xzqdm=b.xzqdm  ORDER BY b.xzqdm ";
                    sqltitle = $@"  select  '序号' label,'index' prop   
 union all 
 select  '区' label,'xzq' prop  
  union all 
 select  '房屋总数' label,'fwds' prop 
   union all 
 select  '今日自查总数' label,'t' prop 
    union all 
 select  date (CURRENT_DATE - INTERVAL '1 day')::text label,'t1' prop 
     union all 
 select  date (CURRENT_DATE - INTERVAL '2 day')::text label,'t2' prop 
     union all 
 select  date (CURRENT_DATE - INTERVAL '3 day')::text label,'t3' prop 
     union all 
 select  date (CURRENT_DATE - INTERVAL '4 day')::text label,'t4' prop 
     union all 
 select  date (CURRENT_DATE - INTERVAL '5 day')::text label,'t5' prop 
     union all 
 select  date (CURRENT_DATE - INTERVAL '6 day')::text label,'t6' prop  ";
                }
                if (lea == 9)
                {
                    sql = @$"select 
CONCAT('[', STRING_AGG(CAST(zczs AS VARCHAR), ', ' ), ']') AS zczs,
 CONCAT('[', STRING_AGG(CAST(yhcount AS VARCHAR), ', ' ), ']') AS yhcount,
 CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ), ']') AS zgcount from
(select  (select count(1) zczs from zm_pc_yhlog a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.towndm like @code )  ,
(select count(1) yhcount from zm_pc_yhlog_dx_cj a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.towndm like @code),
(select count(1) zgcount  from zm_pc_yhlog_dxzgson_cj a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.towndm like @code))a
";
                }
                if (lea == 12)
                {
                    sql = @$" select 
CONCAT('[', STRING_AGG(CAST(zczs AS VARCHAR), ', ' ), ']') AS zczs,
 CONCAT('[', STRING_AGG(CAST(yhcount AS VARCHAR), ', ' ), ']') AS yhcount,
 CONCAT('[', STRING_AGG(CAST(zgcount AS VARCHAR), ', ' ), ']') AS zgcount from
(select  (select count(1) zczs from zm_pc_yhlog a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.villagedm like @code )  ,
(select count(1) yhcount from zm_pc_yhlog_dx_cj a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.villagedm like @code),
(select count(1) zgcount  from zm_pc_yhlog_dxzgson_cj a,zm_building_ledger b where a.villagedm=b.villagedm and date(create_on) = (CURRENT_DATE) and b.villagedm like @code))a    ";
                }
                var data = _dbContext.Database.GetDbConnection().Query<object>(sql, new { @code = "%" + param + "%" });
                var columns = _dbContext.Database.GetDbConnection().Query<object>(sqltitle, new { @code = "%" + param + "%" });
                var hj = _dbContext.Database.GetDbConnection().Query<object>(countsql, new { @code = "%" + param + "%" }).FirstOrDefault();
                var res = new RespRet<object>(true, "Ok", new { data = data, columns = columns, hj = hj });
                //WriteSystemLog(usernNumber, "houses/zcqk", res);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), new { param = param });
                WriteSystemLog(usernNumber, "houses/zcqk", res);
                res.Msg = "系统异常";
                return res;
            }
        }




        private byte[] GetDynamicVectorTile(int z, int x, int y)
        {
            //            var sql = @$"SELECT 
            //ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
            //FROM 
            //(SELECT 
            //ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom, 
            //id,fwbh,yhfwbh,address,pczt_housing as pcztHousing,pczt_fire as pcztjc,pczt_police as pcztPolice 
            //FROM zm_buildings 
            //WHERE ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";



            DateTime dstartDate = DateTime.Parse("2023-02-09 00:00:00");
            DateTime dendDate = DateTime.Parse("2024-03-09 00:00:00");
            dstartDate = dstartDate.AddDays(1).AddSeconds(-1);

            var sql = @$"SELECT 
            ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
            FROM 
            (
                SELECT
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom,
            	zm_buildings.ID,
            	zm_buildings.fwbh,
            	zm_buildings.yhfwbh,
            	zm_buildings.address,
        CASE  
        WHEN EXISTS (  
            SELECT 1  
            FROM zm_pc_yhlog_dx  
            WHERE zm_pc_yhlog_dx.fwbh = zm_buildings.fwbh AND zm_pc_yhlog_dx.zg_value = 0  
        ) THEN 0  
        ELSE 1  
    END AS pcztzc, 

         CASE  
        WHEN EXISTS (  
            SELECT 1  
            FROM zm_pc_yhlog_dx_cj  
            WHERE zm_pc_yhlog_dx_cj.fwbh = zm_buildings.fwbh AND zm_pc_yhlog_dx_cj.zg_value = 0  
        ) THEN 0  
        ELSE 1  
    END AS pcztjc, 
            	zm_pc_yhlog_dx.zg_value AS pcztPolice 
            FROM
            	zm_buildings
            	LEFT JOIN ( SELECT fwbh, SUM ( zg_value ) AS zg_value FROM zm_pc_yhlog_dx GROUP BY fwbh ) AS zm_pc_yhlog_dx ON zm_buildings.fwbh = zm_pc_yhlog_dx.fwbh
            	LEFT JOIN  ( SELECT fwbh, SUM ( zg_value ) AS zg_value FROM zm_pc_yhlog_dx_cj GROUP BY fwbh ) AS zm_pc_yhlog_dx_cj ON zm_buildings.fwbh = zm_pc_yhlog_dx_cj.fwbh 
            WHERE ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326)) 
        AND  geom IS NOT NULL
        AND NOT ST_IsEmpty(geom)
        AND ST_IsValid(ST_MakeValid(geom))
) AS P";



            //            var sql = @$"SELECT 
            //ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
            //FROM 
            //(
            //    SELECT
            //    ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom,
            //	zm_buildings.ID,
            //	zm_buildings.fwbh,
            //	zm_buildings.yhfwbh,
            //	zm_buildings.address,
            //CASE

            //		WHEN ( map_yh.pczt  ='2' ) THEN
            //		0 ELSE 1 
            //	END AS pcztzc,
            //	map_yh.jcyhcount,
            //	map_yh.zcyhcount
            //FROM
            //	zm_buildings
            //	LEFT JOIN map_yh ON map_yh.fwbh = zm_buildings.fwbh

            //WHERE ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";


            var tile = _dbContext.Database.GetDbConnection().Query<byte[]>(sql).FirstOrDefault();
            return tile;
        }

        private byte[] GetDynamicVectorTile__build(int z, int x, int y)
        {





            var userNumber = this.CurrentUser();

            if (string.IsNullOrEmpty(userNumber))
            {
                return null;
            }
            var sql = "";
            var user = _userRepository.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1);
            var roleType = (PermissionRoleType)user.RoleType;
            var codeWhere = Utilitys.GetLikeSqlWhere_yt(user.Jurisdiction, null);
            if (roleType == PermissionRoleType.Admin || string.IsNullOrEmpty(codeWhere))
            {
                sql = @$"SELECT 
                ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
                FROM 
                (SELECT 
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom, 
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( 17, 107880, 49659),4096,256,FALSE) AS geom, 
                 zb.build_no,zb.build_name,zb.district_id,zb.district_name,zb.street_name,zb.street_id2021,zb.jcnd from  zm_yt_build  zb, zm_yt_buildmap zbm
                where zb.build_no =zbm.pfhouseid and ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";

            }
            else
            {

                if (!string.IsNullOrEmpty(codeWhere))
                {
                    sql = @$"SELECT 
                ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
                FROM 
                (SELECT 
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom, 
                ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( 17, 107880, 49659),4096,256,FALSE) AS geom, 
                 zb.build_no,zb.build_name,zb.district_id,zb.district_name,zb.street_name,zb.street_id2021,zb.jcnd from  zm_yt_build  zb, zm_yt_buildmap zbm
                where " + codeWhere + @$" and  zb.build_no =zbm.pfhouseid and ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";

                }

            }

            var tile = _dbContext.Database.GetDbConnection().Query<byte[]>(sql).FirstOrDefault();
            return tile;



        }


        private byte[] GetRiskHouseDynamicVectorTile(int z, int x, int y)
        {
            var sql = @$"SELECT 
ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile 
FROM 
(SELECT 
ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom,fwyt, 
id,fwbh,yhfwbh,address,result,city_result as cityResult,aqyhcp 
FROM risk_census_house_yhpc 
WHERE ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope( {z}, {x}, {y}), 4326))) AS P";
            var tile = _dbContext.Database.GetDbConnection().Query<byte[]>(sql).FirstOrDefault();
            return tile;
        }



        /// <summary>
        /// 车辆与充电设施配比情况
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>

        [HttpPost("houses/clycdsspbqk")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> clycdsspbqk([FromBody] DateQuery param)
        {
            if (string.IsNullOrWhiteSpace(param.code))
            {
                param.code = "110000";
            }
        

            string time = DateTime.Today
 .AddHours(23)
 .AddMinutes(59)
 .AddSeconds(59)
 .ToString("yyyy-MM-dd HH:mm:ss");

            DateTime endtime = DateTime.Today
.AddHours(23)
.AddMinutes(59)
.AddSeconds(59);

            DateTime startTime = DateTime.ParseExact(
    "2024-01-01",
    "yyyy-MM-dd",
    CultureInfo.InvariantCulture
);

            string table_name = "zm_building_fwzt_" + DateTime.Now.Year;


            param.code = param.code.Substring(param.code.Length - 3) == "000" ? param.code.Substring(0, param.code.Length - 3) : param.code;
            string sql = @$" select * from				 			 			 
(select COALESCE(sum(qcxycdjk),0)+COALESCE(sum(tzzfybjcdssjk),0)  cdjksl,count(case when sfsqfwftcf=1 then 1 end) sqfwfsl  from zm_pc_gjzz_cj WHERE  date(create_on) between @startime and @endtime::TIMESTAMP)  t1
,			 				
(select COALESCE(sum(a.czryrs),0)czryrs from zm_pc_base a where a.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           ) and     a.create_on between @startime and @endtime::TIMESTAMP  ) t2  ";
            string sqldata = @$" select code	xzqdm,name xzq	,bdfwjzrydddzxcsl,	cdjksl,	sqfwfsl	,xy	,xd	,dy From ( select t1.*,bdfwjzrydddzxcsl,COALESCE(cdjksl,0) cdjksl,COALESCE(sqfwfsl,0) sqfwfsl,COALESCE(xy,0) xy,COALESCE(xd,0) xd,COALESCE(dy,0) dy from (SELECT DISTINCT zm_buildings.xzqdm code,
            zm_buildings.xzq name
           FROM zm_buildings) t1 left join				 			 			 
(select COALESCE(sum(qcxycdjk),0)+COALESCE(sum(tzzfybjcdssjk),0)  cdjksl,
count(case when sfsqfwftcf=1 then 1 end) sqfwfsl,xzqdm,
count(case when cddf=3 then 1 end)+count(case when bjcdssdfqk=3 then 1 end) xy,
count(case when cddf=2 then 1 end)+count(case when bjcdssdfqk=2 then 1 end) xd,
count(case when cddf=1 then 1 end)+count(case when bjcdssdfqk=1 then 1 end) dy
from zm_pc_gjzz_cj WHERE  create_on between @startime and @endtime  GROUP BY xzqdm) t2 on t1.code
=t2.xzqdm       left join 
 ( SELECT t1.xzqdm,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
            zm_buildings.xzq,
            zm_buildings.xzqdm
           FROM 					zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )
          GROUP BY zm_buildings.xzqdm, zm_buildings.xzq
          ORDER BY zm_buildings.xzqdm) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.xzq,
            zm_pc_base.xzqdm
           FROM  (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE   fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )	
          GROUP BY zm_pc_base.xzqdm, zm_pc_base.xzq) t2 ON (((t1.xzqdm)::text = (t2.xzqdm)::text))) left join (select t1.xzqdm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1 left join zm_pc_base_cj t2 on t1.fwbh=t2.fwbh where t1.create_on between @startime and @endtime and fwzt is null GROUP BY t1.xzqdm) t3 on t2.xzqdm=t3.xzqdm) t3 on t1.code=t3.xzqdm ORDER BY t3.xzqdm)a ";
            param.code = param.code.Substring(param.code.Length - 3) == "000" ? param.code.Substring(0, param.code.Length - 3) : param.code;
            var lea = param.code.Substring(param.code.Length - 3) == "000" ? param.code.Length - 3 : param.code.Length;
            if (lea == 6)
            {
                sqldata = @$" select  code	towndm,name town,xzqdm,xzq	,bdfwjzrydddzxcsl,	cdjksl,	sqfwfsl	,xy	,xd	,dy from( select t1.*,bdfwjzrydddzxcsl,COALESCE(cdjksl,0) cdjksl,COALESCE(sqfwfsl,0) sqfwfsl,COALESCE(xy,0) xy,COALESCE(xd,0) xd,COALESCE(dy,0) dy from (
  SELECT DISTINCT a.xzq,a.xzqdm, a.towndm code,b.region_name name FROM zm_buildings a,zm_department b where a.towndm=b.region_code and b.regional_level='6'
 ) t1 left join				 			 			 
(select COALESCE(sum(qcxycdjk),0)+COALESCE(sum(tzzfybjcdssjk),0)  cdjksl,
count(case when sfsqfwftcf=1 then 1 end) sqfwfsl,towndm,
count(case when cddf=3 then 1 end)+count(case when bjcdssdfqk=3 then 1 end) xy,
count(case when cddf=2 then 1 end)+count(case when bjcdssdfqk=2 then 1 end) xd,
count(case when cddf=1 then 1 end)+count(case when bjcdssdfqk=1 then 1 end) dy
from zm_pc_gjzz_cj WHERE  create_on between @startime and @endtime  GROUP BY towndm) t2 on t1.code
=t2.towndm left join 
 ( SELECT t1.towndm,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
           max(zm_buildings.town),
            zm_buildings.towndm
           FROM 					zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )
          GROUP BY zm_buildings.towndm
          ORDER BY zm_buildings.towndm) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.town
           FROM  (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE   fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )	
          GROUP BY zm_pc_base.town) t2 ON (((t1.towndm)::text = (t2.town)::text))) left join (select t1.towndm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1 left join zm_pc_base_cj t2 on t1.fwbh=t2.fwbh where t1.create_on between @startime and @endtime and fwzt is null GROUP BY t1.towndm) t3 on t1.towndm=t3.towndm ) t3 on t1.code=t3.towndm where t1.code like @code)a ";
            }
            if (lea == 9)
            {
                sql = @$" 					
				select t1.*,COALESCE(cdjksl,0) cdjksl,COALESCE(sqfwfsl,0) sqfwfsl,COALESCE(czryrs,0)czryrs from (
  SELECT DISTINCT a.towndm code,b.region_name name FROM zm_buildings a,zm_department b where a.towndm=b.region_code and b.regional_level='6'
 ) t1 left join				 			 			 
(select COALESCE(sum(qcxycdjk),0)+COALESCE(sum(tzzfybjcdssjk),0)  cdjksl,count(case when sfsqfwftcf=1 then 1 end) sqfwfsl,towndm  from zm_pc_gjzz_cj WHERE  create_on between @startime and @endtime GROUP BY towndm) t2 on t1.code
=t2.towndm
	left join 				 				
(select  sum(a.czryrs)czryrs,a.town towndm from zm_pc_base a where a.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )    and a.create_on between @startime and @endtime GROUP BY a.town) t3 on t1.code=t3.towndm where t1.code like @code 	
					
 ";
                sqldata = @$" select towndm,town,xzqdm xzq,  code	villagedm,name village	,bdfwjzrydddzxcsl,	cdjksl,	sqfwfsl	,xy	,xd	,dy From ( select t1.*,bdfwjzrydddzxcsl,COALESCE(cdjksl,0) cdjksl,COALESCE(sqfwfsl,0) sqfwfsl,COALESCE(xy,0) xy,COALESCE(xd,0) xd,COALESCE(dy,0) dy from (SELECT  a.villagedm code,max(b.region_name) name,max(xzqdm) xzqdm,max(xzq) xzq,max(towndm) towndm,max(town) town FROM zm_buildings a,zm_department b where a.villagedm=b.region_code and b.regional_level='7' group by a.villagedm
 ) t1 left join				 			 			 
(select COALESCE(sum(qcxycdjk),0)+COALESCE(sum(tzzfybjcdssjk),0)  cdjksl,
count(case when sfsqfwftcf=1 then 1 end) sqfwfsl,villagedm,
count(case when cddf=3 then 1 end)+count(case when bjcdssdfqk=3 then 1 end) xy,
count(case when cddf=2 then 1 end)+count(case when bjcdssdfqk=2 then 1 end) xd,
count(case when cddf=1 then 1 end)+count(case when bjcdssdfqk=1 then 1 end) dy
from zm_pc_gjzz_cj WHERE  date(create_on) between @startime and @endtime  GROUP BY villagedm) t2 on t1.code
=t2.villagedm left join 
 ( SELECT t1.villagedm,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
           max(zm_buildings.village),
            zm_buildings.villagedm
           FROM 					zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )
          GROUP BY zm_buildings.villagedm
          ) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.village
           FROM 			 (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE   fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )	
          GROUP BY zm_pc_base.village) t2 ON (((t1.villagedm)::text = (t2.village)::text))) left join (select t1.villagedm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1 left join zm_pc_base_cj t2 on t1.fwbh=t2.fwbh where t1.create_on between @startime and @endtime and fwzt is null GROUP BY t1.villagedm) t3 on t1.villagedm=t3.villagedm
          ) t3 on t1.code=t3.villagedm where t1.code like @code)a ";

            }
            if (lea == 12)
            {
                sql = @$" 					
				select t1.*,COALESCE(cdjksl,0) cdjksl,COALESCE(sqfwfsl,0) sqfwfsl,COALESCE(czryrs,0)czryrs from (
  SELECT DISTINCT a.towndm code,b.region_name name FROM zm_buildings a,zm_department b where a.towndm=b.region_code and b.regional_level='6'
 ) t1 left join				 			 			 
(select COALESCE(sum(qcxycdjk),0)+COALESCE(sum(tzzfybjcdssjk),0)  cdjksl,count(case when sfsqfwftcf=1 then 1 end) sqfwfsl,towndm  from zm_pc_gjzz_cj WHERE  create_on between @startime and @endtime GROUP BY towndm) t2 on t1.code
=t2.towndm
	left join 				 				
(select  sum(a.czryrs)czryrs,a.town towndm from zm_pc_base a where a.fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )    and a.create_on between @startime and @endtime GROUP BY a.town) t3 on t1.code=t3.towndm where t1.code like @code 	
					
 ";
                sqldata = @$" select towndm,town,xzqdm xzq,  code	villagedm,name village	,bdfwjzrydddzxcsl,	cdjksl,	sqfwfsl	,xy	,xd	,dy from ( select t1.*,bdfwjzrydddzxcsl,COALESCE(cdjksl,0) cdjksl,COALESCE(sqfwfsl,0) sqfwfsl,COALESCE(xy,0) xy,COALESCE(xd,0) xd,COALESCE(dy,0) dy from (SELECT a.villagedm code,max(b.region_name) name,max(xzqdm) xzqdm,max(xzq) xzq,max(towndm) towndm,max(town) town FROM zm_buildings a,zm_department b where a.villagedm=b.region_code and b.regional_level='7' group by a.villagedm
 ) t1 left join				 			 			 
(select COALESCE(sum(qcxycdjk),0)+COALESCE(sum(tzzfybjcdssjk),0)  cdjksl,
count(case when sfsqfwftcf=1 then 1 end) sqfwfsl,villagedm,
count(case when cddf=3 then 1 end)+count(case when bjcdssdfqk=3 then 1 end) xy,
count(case when cddf=2 then 1 end)+count(case when bjcdssdfqk=2 then 1 end) xd,
count(case when cddf=1 then 1 end)+count(case when bjcdssdfqk=1 then 1 end) dy
from zm_pc_gjzz_cj WHERE  date(create_on) between @startime and @endtime  GROUP BY villagedm) t2 on t1.code
=t2.villagedm left join 
 ( SELECT t1.villagedm,
    COALESCE(t2.bdfwjzrydddzxcsl, (0)::bigint) AS bdfwjzrydddzxcsl
   FROM (( SELECT count(1) AS zcount,
           max(zm_buildings.village),
            zm_buildings.villagedm
           FROM 					zm_buildings where  fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )
          GROUP BY zm_buildings.villagedm
          ) t1
     LEFT JOIN ( SELECT 
            sum(zm_pc_base.bdfwjzrydddzxcsl) AS bdfwjzrydddzxcsl,
            zm_pc_base.village
           FROM  (select t1.*  From zm_pc_yh t0  join zm_pc_base t1 on t0.fwbh=t1.fwbh  where t1.create_on between @startime and @endtime::TIMESTAMP)zm_pc_base
          WHERE   fwbh not in (
             SELECT DISTINCT fwbh FROM {table_name} WHERE final_fwzt IS NOT NULL AND final_create_on =@formattedDate
           )	
          GROUP BY zm_pc_base.village) t2 ON (((t1.villagedm)::text = (t2.village)::text))) left join (select t1.villagedm,count(distinct t1.fwbh) zccount from zm_pc_yhlog t1 left join zm_pc_base_cj t2 on t1.fwbh=t2.fwbh where t1.create_on between @startime and @endtime and fwzt is null GROUP BY t1.villagedm) t3 on t1.villagedm=t3.villagedm
          ) t3 on t1.code=t3.villagedm where t1.code like @code)a ";
            }
            var msg = _dbContext.Database.GetDbConnection().Query<object>(sql, new {  @formattedDate = time , @code = "%" + param.code + "%", @startime =startTime, @endtime =endtime }).FirstOrDefault();
            var data = _dbContext.Database.GetDbConnection().Query<object>(sqldata, new { @formattedDate = time ,@code = "%" + param.code + "%", @startime = startTime, @endtime =endtime }).ToList();
            return new RespRet<object>(true, "Ok", new { msg = msg, data = data });
        }
    }
}
#endregion